最小生成樹 模版
阿新 • • 發佈:2017-08-19
can div node n) def str ostream () clu
//Gang #include<iostream> #include<cstring> #include<algorithm> #include<cstdio> #include<cstdlib> #include<cmath> #define FOR(x,y,z) for(int x=y;x<=z;x++) #define REP(x,y,z) for(int x=y;x>=z;x--) #define ll long long int n,m; int fa[200005]; int find(intx) { int p,temp; p=x; while(x!=fa[x]) { x=fa[x]; } while(x!=p) { temp=fa[p]; fa[p]=x; p=temp; } return x; } struct node { int x,y,z; } e[200005]; int cmp(node a,node b) { return a.z<b.z; } int tot=0;int ans=0; using namespace std; int main() { scanf("%d%d",&n,&m); FOR(i,1,n) fa[i]=i; FOR(i,1,m) scanf("%d%d%d",&e[i].x,&e[i].y,&e[i].z); sort(e+1,e+m+1,cmp); FOR(i,1,m) { int dx=find(e[i].x),dy=find(e[i].y); if(dx!=dy) { tot++; fa[dx]=dy; ans+=e[i].z; } if(tot==n-1) { printf("%d\n",ans); return 0; } } printf("orz\n"); return 0; }
最小生成樹 模版