Constructing Roads-最小生成树(kruskal)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1102

题目描述:

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<algorithm>
 4 using namespace std;
 5 
 6 struct node
 7 {
 8     int u,v,cost;
 9 }a[10005];
10 int pre[105];
11 int fin(int x)
12 {
13     if(x==pre[x])
14     {
15         return x;
16     }
17     else
18     {
19         return pre[x]=fin(pre[x]);
20     }
21 }
22 
23 void join(int x,int y)
24 {
25     int t1=fin(x);
26     int t2=fin(y);
27     if(t1!=t2)
28     {
29         pre[t1]=t2;
30     }
31 }
32 
33 bool cmp(node x,node y)
34 {
35     return x.cost<y.cost;
36 }
37 
38 int main()
39 {
40     int n;
41     while(~scanf("%d",&n))
42     {
43         for(int i=0;i<=n;i++)
44         {
45             pre[i]=i;
46         }
47         int num,cnt=0;;
48         for(int i=1;i<=n;i++)
49         {
50             for(int j=1;j<=n;j++)
51             {
52                 scanf("%d",&num);
53                 a[cnt].u=i;
54                 a[cnt].v=j;
55                 a[cnt].cost=num;
56                 cnt++;
57             }
58         }
59         sort(a,a+cnt,cmp);
60         int sum1=0,sum=0;//此处算是一个小剪枝吧
61         int q;
62         scanf("%d",&q);
63         int c,d;
64         for(int i=0;i<q;i++)
65         {
66             scanf("%d%d",&c,&d);
67             if(fin(c)!=fin(d))
68             {
69                 join(c,d);//已经修好路的村庄链接成一个集合
70                 sum1++;
71             }
72         }
73         for(int i=0;i<cnt;i++)
74         {
75             if(fin(a[i].u)!=fin(a[i].v))
76             {
77                 join(a[i].u,a[i].v);
78                 sum+=a[i].cost;
79                 sum1++;
80             }
81             if(sum1==n-1)
82             {
83                 break;
84             }
85         }
86         printf("%d\n",sum);
87     }
88     return 0;
89 }

猜你喜欢

转载自www.cnblogs.com/LJHAHA/p/10344037.html