poj 1287 Networking (最小生成树Kruskal算法)
最小生成树裸题
https://vjudge.net/contest/245213#problem/B
#include <iostream> #include <cstring> #include <cstdio> #include <algorithm> using namespace std; const int maxn=55; const int maxm=110000; int F[maxn]; struct Edge{ int u,v,w; }edge[maxm]; int tol; void addedge(int u,int v,int w) { edge[tol].u=u; edge[tol].v=v; edge[tol++].w=w; } bool cmp(Edge a,Edge b) { return a.w<b.w; } int Find(int x) { if(F[x]==-1) return x; else return F[x]=Find(F[x]); } int Kruskal(int n) { memset(F,-1,sizeof(F)); sort(edge,edge+tol,cmp); int cnt=0; int ans=0; for(int i=0;i<tol;i++) { int u=edge[i].u; int v=edge[i].v; int w=edge[i].w; int t1=Find(u); int t2=Find(v); if(t1!=t2) { ans+=w; F[t1]=t2; cnt++; } if(cnt==n-1) break; } if(cnt<n-1) return -1; else return ans; } int main() { int n,m; while(~scanf("%d",&n)&&(n)) { memset(edge,0,sizeof(edge)); scanf("%d",&m); for(int i=0;i<m;i++) { int u,v,w; scanf("%d%d%d",&u,&v,&w); addedge(u,v,w); } int ans=Kruskal(n); printf("%d\n",ans); } return 0; }