传送门:http://poj.org/problem?id=1287
解题思路:
简答的最小生成树
实现代码:
#include <iostream> #include <cstdio> #include <algorithm> using namespace std; const int maxn=10000; struct Edges{ int u,v,w; bool operator <(const Edges &rhs)const{ return w<rhs.w; } }edges[maxn*maxn]; int p[maxn]; int findfa(int a){ if(p[a]!=a) p[a]=findfa(p[a]); return p[a]; } void unit(int a,int b){ int fa=findfa(p[a]); int fb=findfa(p[b]); if(fa!=fb){ p[fa]=fb; } } void init(int N){ for(int i=0;i<=N;i++) p[i]=i; } int Kruskal(int P,int R){ init(P); int ans=0; sort(edges,edges+R); for(int i=0;i<R;i++){ if(findfa(edges[i].u)!=findfa(edges[i].v)){ ans+=edges[i].w; unit(edges[i].u,edges[i].v); } } return ans; } int main(){ int P,R; while(scanf("%d%d",&P,&R)!=EOF&&P){ int m=0; for(int i=0;i<R;i++){ scanf("%d%d%d",&edges[i].u,&edges[i].v,&edges[i].w); } printf("%d ",Kruskal(P,R)); } }