标签:namespace const logs cstring names == blog ret ios
#include<iostream> #include<algorithm> #include<cstdio> #include<cstdlib> #include<cstring> #include<cmath> using namespace std; int f[100000]; struct node { int a; int b; int c; }s[100000]; bool cmp(const node & x,const node & y){return x.c<y.c;} int fuqin(int h) { if(f[h]==h) return h; else { f[h]=fuqin(f[h]); return f[h]; } } int main() { int n; int m; cin>>n>>m; int i,j,k; for(i=1;i<=m;i++) { cin>>s[i].a>>s[i].b>>s[i].c; } for(i=1;i<=n;i++) f[i]=i; sort(s+1,s+m+1,cmp); int ans=0,maxx=0; for(i=1;i<=m;i++) { int h1=fuqin(s[i].a); int h2=fuqin(s[i].b); if(h1!=h2) { f[h2]=h1; maxx++; ans+=s[i].c; } if(maxx==n-1) break; } cout<<ans; return 0; } /* 5 6 1 2 2 2 3 1 2 3 2 3 4 3 4 5 2 5 4 9 */
克鲁斯卡尔的核心是,给边排序。选出每两个点的最短路径。直到图连通,需要n-1条边。
标签:namespace const logs cstring names == blog ret ios
原文地址:http://www.cnblogs.com/WWHHTT/p/7693524.html