题目:给出一个无向图,求出最小生成树,如果该图不连通,则输出orz。
解法:Kruskal求MST。
1 #include<cstdio> 2 #include<cstdlib> 3 #include<cstring> 4 #include<iostream> 5 #include<algorithm> 6 using namespace std; 7 8 const int N=5010,M=200010; 9 int fa[N]; 10 struct edge{int x,y,d;}a[M]; 11 12 int ffind(int x) 13 { 14 if (fa[x]!=x) fa[x]=ffind(fa[x]); 15 return fa[x]; 16 } 17 bool cmp(edge x,edge y) {return x.d<y.d;} 18 int main() 19 { 20 int n,m; 21 scanf("%d%d",&n,&m); 22 int x,y,d; 23 for (int i=1;i<=m;i++) 24 scanf("%d%d%d",&a[i].x,&a[i].y,&a[i].d); 25 sort(a+1,a+1+m,cmp); 26 for (int i=1;i<=n;i++) fa[i]=i; 27 int sum=0,cnt=0; 28 for (int i=1;i<=m;i++) 29 { 30 int x=a[i].x,y=a[i].y; 31 int xx=ffind(x),yy=ffind(y); 32 if (xx!=yy) 33 { 34 fa[xx]=yy; 35 sum+=a[i].d; 36 cnt++; 37 if (cnt==n-1) break; 38 } 39 } 40 if (cnt==n-1) printf("%d ",sum); 41 else printf("orz "); 42 return 0; 43 }