【Kruscal最小生成树】D. Jungle Roads

https://www.bnuoj.com/v3/contest_show.php?cid=9154#problem/D

【Accepted】

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<string>
 5 #include<cmath>
 6 #include<algorithm>
 7 #include<queue>
 8 #include<map>
 9 using namespace std;
10 const int maxn=30;
11 const int maxm=maxn*maxn;
12 char str[5];
13 int fa[maxn];
14 int n,m;
15 struct edge
16 {
17     int u;
18     int v;
19     int c;
20     bool operator<(const edge& a) const
21     {
22         return c<a.c;
23     }
24 }e[maxm];
25 int tot;
26 void init()
27 {
28     tot=0;
29     for(int i=0;i<maxn;i++)
30     {
31         fa[i]=i;
32     }
33  } 
34 int find(int x)
35 {
36     return fa[x]==x?x:fa[x]=find(fa[x]);
37 }
38 void add(int u,int v,int c)
39 {
40     e[tot].u=u;
41     e[tot].v=v;
42     e[tot++].c=c;
43 }
44 int Kruscal()
45 {
46     sort(e,e+tot);
47     int cnt=0;
48     int ans=0;
49     for(int i=0;i<tot;i++)
50     {
51         if(cnt==n-1)
52         {
53             break;
54         }
55         int fx=find(e[i].u);
56         int fy=find(e[i].v);
57         if(fx!=fy)
58         {
59             fa[fy]=fx;
60             ans+=e[i].c;
61             cnt++;
62         }
63     }
64     return ans;
65 }
66 int main()
67 {
68     
69     while(~scanf("%d",&n))
70     {
71         if(n==0)
72         {
73             break;
74         }
75         init();
76         for(int i=0;i<n-1;i++)
77         {
78             scanf("%s%d",str,&m);
79             int u=str[0]-'A';
80             while(m--)
81             {
82                 int c;
83                 scanf("%s%d",str,&c);
84                 int v=str[0]-'A';
85                 add(u,v,c);
86             }
87         }
88         int ans=Kruscal();
89         printf("%d
",ans);
90     }
91     return 0;    
92 }
View Code
原文地址:https://www.cnblogs.com/itcsl/p/7191110.html