HDU1863(Kruskal+并查集水题)

https://cn.vjudge.net/problem/HDU-1863

省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可)。经过调查评估,得到的统计表中列出了有可能建设公路的若干条道路的成本。现请你编写程序,计算出全省畅通需要的最低成本。

Input测试输入包含若干测试用例。每个测试用例的第1行给出评估的道路条数 N、村庄数目M ( < 100 );随后的 N
行对应村庄间道路的成本,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间道路的成本(也是正整数)。为简单起见,村庄从1到M编号。当N为0时,全部输入结束,相应的结果不要输出。
Output对每个测试用例,在1行里输出全省畅通需要的最低成本。若统计数据不足以保证畅通,则输出“?”。
Sample Input

3 3
1 2 1
1 3 2
2 3 4
1 3
2 3 2
0 100

Sample Output

3
?
 1 #include<bits/stdc++.h>
 2 #define maxn 110
 3 using namespace std;
 4 int n,m,tot;
 5 int parent[maxn];
 6 int ans;
 7 struct edge
 8 {
 9     int u,v,w;
10 }EV[5050];
11 bool cmp(edge a,edge b)
12 {
13     return a.w<b.w;
14 }
15 int Find(int x)
16 {
17     if(parent[x]==-1)
18         return x;
19     else
20         return Find(parent[x]);
21 }
22 void kruskal()
23 {
24     memset(parent,-1,sizeof parent);
25     sort(EV+1,EV+m+1,cmp);
26     for(int i=1;i<=m;i++)
27     {
28         int t1=Find(EV[i].u);
29         int t2=Find(EV[i].v);
30         if(t1!=t2)
31         {
32             ans+=EV[i].w;
33             parent[t1]=t2;
34             tot++;
35         }
36     }
37 }
38 int main()
39 {
40     while(~scanf("%d%d",&m,&n)&&m)
41     {
42     for(int i=1;i<=m;i++)
43         cin>>EV[i].u>>EV[i].v>>EV[i].w;
44     ans=0;
45     tot=0;
46     kruskal();
47     if(tot!=n-1)
48         cout<<"?"<<endl;
49     else
50         cout<<ans<<endl;
51     }
52     return 0;
53 }


猜你喜欢

转载自www.cnblogs.com/zuiaimiusi/p/10727283.html
今日推荐