思路:并查集板子。
#include<cstdio> #include<cstring> #include<iostream> #include<algorithm> using namespace std; int fa[60]; int n,m,tot,sum; struct nond{ int x,y,z; }v[2600]; int cmp(nond a,nond b){ return a.z<b.z; } int find(int x){ if(fa[x]==x) return x; else return fa[x]=find(fa[x]); } int main(){ while(scanf("%d%d",&n,&m)&&n){ for(int i=1;i<=m;i++) scanf("%d%d%d",&v[i].x,&v[i].y,&v[i].z); sort(v+1,v+1+m,cmp); for(int i=1;i<=n;i++) fa[i]=i; for(int i=1;i<=m;i++){ int dx=find(v[i].x); int dy=find(v[i].y); if(dx==dy) continue; tot++; fa[dy]=dx; sum+=v[i].z; if(tot==n-1) break; } cout<<sum<<endl;sum=0;tot=0; } }