zoj1586QS Network

题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=1586

模板题。

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<algorithm>
 4 using namespace std;
 5 const int maxn=1010;
 6 int f[maxn],c[maxn];
 7 int n,w;
 8 struct edge
 9 {
10     int u,v,w;
11     bool operator <(const edge &a)
12     {
13         return w<a.w;
14     }
15 }e[maxn*maxn];
16 void init()
17 {
18     for(int i=1;i<=n;i++)
19         f[i]=i;
20 }
21 int gf(int x)
22 {
23     return x==f[x]?x:f[x]=gf(f[x]);
24 }
25 void uni(int a,int b)
26 {
27     int pa=gf(a);
28     int pb=gf(b);
29     f[pb]=pa;
30 }
31 int main()
32 {
33 
34     int t;
35     scanf("%d",&t);
36     while(t--){
37         int ans=0;
38         scanf("%d",&n);
39         for(int i=1;i<=n;i++)
40             scanf("%d",&c[i]);
41         init();
42         int cnt=0;
43         for(int i=1;i<=n;i++)
44         for(int j=1;j<=n;j++){
45             scanf("%d",&w);
46             e[cnt].u=i;
47             e[cnt].v=j;
48             e[cnt].w=w+c[i]+c[j];
49             cnt++;
50         }
51         sort(e,e+cnt);
52         for(int i=0;i<cnt;i++)
53         {
54             edge t=e[i];
55             if(gf(t.u)!=gf(t.v))
56             {
57                 ans+=t.w;
58                 uni(t.u,t.v);
59             }
60         }
61         printf("%d
",ans);
62 
63     }
64 }
原文地址:https://www.cnblogs.com/yijiull/p/6614118.html