P2330 繁忙的城市(krusal最小生成树)

直接干

 1 #include<iostream>
 2 #include<algorithm>
 3 #include<climits>
 4 using namespace std;
 5 struct edge
 6 {
 7     int from,to,weight;
 8 }a[100010];//存边
 9 int fa[310];//存并查集
10 bool cmp(edge a,edge b)
11 {
12     return a.weight<b.weight;
13 }
14 int finds(int x)//本来以为还需要路径压缩的
15 {
16     while(fa[x]!=x)
17     {
18         x=fa[x];
19     }
20     return x;
21 }
22 int main(void)
23 {
24     int n,m;
25     cin>>n>>m;
26     for(int i=0;i<m;i++)
27     {
28         cin>>a[i].from>>a[i].to>>a[i].weight;
29     }
30     sort(a,a+m,cmp);
31     for(int i=1;i<=n;i++)
32         fa[i]=i;//初始化并查集
33     int cnt=0,maxn=INT_MIN;
34     for(int i=0;i<m;i++)
35     {
36         int t1=a[i].from;
37         int t2=a[i].to;
38         int w=a[i].weight;
39         int f1=finds(t1);
40         int f2=finds(t2);
41         if(f1!=f2)
42         {
43             cnt++;//边数加一
44             maxn=max(maxn,w);
45             fa[f1]=f2;
46         }
47     }
48     cout<<cnt<<" "<<maxn;
49     return 0;
50 }

猜你喜欢

转载自www.cnblogs.com/greenofyu/p/12233984.html