九度:1154<最小生成树>

来源:互联网 发布:linux从u盘复制文件 编辑:程序博客网 时间:2024/06/05 11:42

http://ac.jobdu.com/problem.php?pid=1154


// 北大10机试// 1154:Jungle Roads// // WA:原因,初始化时为1~SIZE-1,而使用时ch-'A',是从0开始的。// 但是,本地测试却与答案相同!所以,优点隐蔽。// 所以初始化时,为0~SIZE-1时,就安全保险了。// 还需要养成习惯,做到点的开始为1。除非规定了第一个点为0.#include <stdio.h>#include <algorithm>#define SIZE 30#define MAXSIZE 350using namespace std;struct Edge{int a, b;int cost;bool operator < (const Edge& A) const{return cost < A.cost;}};int fa[SIZE];Edge edge[MAXSIZE];void Init(){for(int i=0; i<SIZE; i++)//扩大初始化范围{fa[i]=i;}}int Getfa(int x){if(x == fa[x])return x;elsefa[x]=Getfa(fa[x]);return fa[x];}int main(){#ifdef ONLINE_JUDGE#elsefreopen("E:\\in.txt", "r", stdin);//freopen("E:\\out.txt", "w", stdout);#endifint n;while(scanf("%d", &n) != EOF && n){Init();int len=0;while(--n>0){char temp;getchar();scanf("%c", &temp);int k;scanf("%d", &k);while(k-->0){char ch;scanf(" %c %d", &ch, &edge[len].cost);edge[len].b=ch-'A';edge[len].a=temp-'A';len++;}}//n-1 lines//printf("len:%d\n", len);sort(edge, edge+len);//for(int j=0;j<len;j++)//{//printf("%c\t%c\t%d\n", edge[j].a+'A', edge[j].b+'A', edge[j].cost);//}int ans=0;for(int i=0;i<len;i++){int x = Getfa(edge[i].a);int y = Getfa(edge[i].b);if( x!=y){fa[x] = y;ans += edge[i].cost;//printf("-");}}printf("%d\n", ans);}return 0;}


0 0