HDU 1102 Constructing Roads 最小生成树

解题报告:要使N个村庄之间都连通,现在已知有一些村庄之间已经连通了,现在在要使所有的村庄都连通,问最少需要的修的路是多少?

感觉这题好坑,prim已知过不了,但是改了克鲁斯卡尔就过了,觉得应该是题目数据有问题。一个简单的题,注意别用prim就是了。

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<iostream>
 4 #include<algorithm>
 5 using namespace std;
 6 
 7 struct node {
 8     int front ,rear,length;
 9 }Rode[10000];
10 int N,Q,tot,a,b,d,par[105];
11 bool cmp(node R1,node R2) {
12     return R1.length < R2.length;
13 }
14 
15 int find(int i) {
16     return i==par[i]? i:par[i] = find(par[i]);
17 }
18 
19 int main( ) {
20     while(scanf("%d",&N)!=EOF) {
21         int k = 0;
22         for(int i = 1;i<=N;++i)
23         for(int j = 1;j<=N;++j) {
24             scanf("%d",&d);
25             if(i >1 && j < i)
26             Rode[++k].front = i,Rode[k].rear = j,Rode[k].length = d;
27         }
28         for(int i = 1;i<=N;++i)
29         par[i] = i;
30         scanf("%d",&Q);
31         while(Q--) {
32             scanf("%d%d",&a,&b);
33             par[find(a)] = find(b);
34         }
35         sort(Rode+1,Rode+k+1,cmp);
36         int tot = 0;
37         for(int i = 1;i<=k;++i) {
38             int x = find(Rode[i].front);
39             int y = find(Rode[i].rear);
40             if(x != y) {
41                 tot += Rode[i].length;
42                 par[x] = y;
43             }
44         }
45         printf("%d
",tot);
46     }
47     return 0;
48 }
View Code
原文地址:https://www.cnblogs.com/xiaxiaosheng/p/3272976.html