[BZOJ1083][SCOI2005]繁忙的都市 最小生成树

题目链接:http://www.lydsy.com/JudgeOnline/problem.php?id=1083

由kruskal算法原理可知,我们对一张无向图做普通的最小生成树,连上的最后一条边就是答案。

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<algorithm>
 4 using namespace std;
 5 int inline readint(){
 6     int Num;char ch;
 7     while((ch=getchar())<'0'||ch>'9');Num=ch-'0';
 8     while((ch=getchar())>='0'&&ch<='9') Num=Num*10+ch-'0';
 9     return Num;
10 }
11 int N,M;
12 struct EDGE{
13     int u,v,w;
14     bool operator < (const EDGE &_)const{
15         return w<_.w;
16     }
17 }edge[50010];
18 int fa[310];
19 int inline getfa(int x){
20     return fa[x]==x?x:fa[x]=getfa(fa[x]);
21 }
22 int main(){
23     N=readint();
24     printf("%d ",N-1);
25     M=readint();
26     for(int i=1;i<=M;i++){
27         edge[i].u=readint();
28         edge[i].v=readint();
29         edge[i].w=readint();
30     }
31     sort(edge+1,edge+1+M);
32     for(int i=1;i<=N;i++) fa[i]=i;
33     int tot=0;
34     for(int i=1;i<=M;i++){
35         int fu=getfa(edge[i].u),
36             fv=getfa(edge[i].v);
37         if(fu==fv) continue;
38         fa[fu]=fv;
39         tot++;
40         if(tot+1==N){
41             printf("%d
",edge[i].w);
42             return 0;
43         }
44     }
45 }
原文地址:https://www.cnblogs.com/halfrot/p/7624327.html