The Head Elder of the tropical island of Lagrishan has a problem. A burst of foreign aid money was spent on extra roads between villages some years ago. But the jungle overtakes roads relentlessly, so the large road network is too expensive to maintain. The Council of Elders must choose to stop maintaining some roads. The map above on the left shows all the roads in use now and the cost in aacms per month to maintain them. Of course there needs to be some way to get between all the villages on maintained roads, even if the route is not as short as before. The Chief Elder would like to tell the Council of Elders what would be the smallest amount they could spend in aacms per month to maintain roads that would connect all the villages. The villages are labeled A through I in the maps above. The map on the right shows the roads that could be maintained most cheaply, for 216 aacms per month. Your task is to write a program that will solve such problems.
9 A 2 B 12 I 25 B 3 C 10 H 40 I 8 C 2 D 18 G 55 D 1 E 44 E 2 F 60 G 38 F 0 G 1 H 35 H 1 I 35 3 A 2 B 10 C 40 B 1 C 20 0
216 30
直接看图就能看出是最小生成树问题,但难点是给出的字母关系转化为数字关系(把地点转化成数字)
代码:
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
struct node{
int u,v,w;
}e[500]; //存放边关系
int n;
int pre[30]; //存放父节点
void init(){ //初始化 pre
int i;
for(i=0;i<=n;i++)
pre[i]=i;
}
int cmp(node a,node b){
return a.w<b.w;
}
int Find(int x){
int r=x;
while(r!=pre[r]) //寻找根节点
r=pre[r];
int i=x,j;
while(i!=r){ //路径压缩
j=pre[i];
pre[i]=r;
i=j;
}
return r;
}
int mix(int a,int b){
int fa=Find(a),fb=Find(b); //如果根节点不同,则把边加入
if(fa!=fb){
pre[fb]=fa;
return 1;
}
return 0;
}
int main(){
while(scanf("%d",&n)!=EOF){
if(n==0) break;
int i;
int cnt=0; //记录总边数
for(i=1;i<=n-1;i++){
char ch[3],sh[3],m; //sh为起点路段一端点 ch 为另一端点 m 为与sh点相关联的点
scanf("%s%d",ch,&m);
int j;
for(j=1;j<=m;j++){
scanf("%s%d",sh,&e[cnt].w);
e[cnt].u=ch[0]-'A';
e[cnt].v=sh[0]-'A';
cnt++;
}
}
init(); //初始化pre
sort(e,e+cnt,cmp); //按照长度从小到大排列,长度小弟优先加入树里
/*for(i=0;i<cnt;i++)
printf("%c-->%c %d\n",e[i].u+'A',e[i].v+'A',e[i].w);*/
int countt=0;
int sum=0;
for(i=0;i<cnt;i++){
if(mix(e[i].u,e[i].v)){
// printf("%c-->%c %d\n",e[i].u+'A',e[i].v+'A',e[i].w);
sum+=e[i].w;
countt++;
}
if(countt==n-1) break; //当边数为顶点数 减去1时 最小树已经完成,跳出循环
}
printf("%d\n",sum);
}
return 0;
}