题意:
还是修路,还是求修路的最小代价。输入第一行是一个小于27的正整数n,代表多少个村庄。然后是n-1行,每行的第一个是一个字母代表一个村庄,然后下一个数字代表这个村庄连接多少个村庄,然后输入每个村庄以及修路的代价。
思路:
修路嘛,一般就是最小生成树。用最常规的方法解就是啦 与以前的不同的是,以前村庄编号都是1,2,3,4这次是A,B,C,D,不过都一样,把输入的字母减去’A’转化成int型就是0,1,2,3了。
#include<iostream>
#include<stdio.h>
#include<string>
#include<climits>
using namespace std;
void prim(int a[100][100],int n)
{
int sum=0;
int *temp=new int[n];
int index=-1;
temp[++index]=0;
while(index<n-1)
{
int min=INT_MAX;
int t=INT_MAX;
for(int i=0;i<=index;i++)
{
for(int j=1;j<n;j++)
{
bool tag=true;
for(int k=0;k<=index;k++)
{
if(j==temp[k])
{
tag=false;
break;
}
}
if(tag)
{
if(a[temp[i]][j]!=-1&&a[temp[i]][j]<min)
{
min=a[temp[i]][j];
t=j;
}
}
}
}
temp[++index]=t;
sum+=min;
}
cout<<sum<<endl;
}
int main()
{
int n,a[100][100];
cin>>n;
while(n!=0)
{
for(int i=0;i<100;i++)
{
for(int j=0;j<100;j++)
{
a[i][j]=-1;
}
}
for(int i=0;i<n-1;i++)
{
char temp1;
int temp2;
cin>>temp1;
cin>>temp2;
//cout<<temp1<<" "<<temp2<<endl;
for(int j=0;j<temp2;j++)
{
char temp3;
int temp4;
cin>>temp3;
cin>>temp4;
//cout<<temp3<<" "<<temp4<<endl;
a[temp1-'A'][temp3-'A']=temp4;
a[temp3-'A'][temp1-'A']=temp4;
}
getchar();
}
prim(a,n);
cin>>n;
}
system("pause");
return 0;
}