最小生成树模板题
跑一次kruskal就可以了
/* ***********************************************
Author :Sun Yuefeng
Created Time :2016/11/9 18:26:37
File Name :tree.cpp
************************************************ */ #include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<string>
#include<bitset>
#include<map>
#include<set>
#include<stack>
#include<vector>
#include<queue>
#include<list>
#define M(a,b) memset(a,b,sizeof(a))
using namespace std;
typedef long long ll;
const int inf=0x3f3f3f3f;
const int maxn=;
const int maxm=;
const int mod=1e7+;
int dx[]= {,,,-,,-,,-};
int dy[]= {,-,,,-,,,-}; int f[maxn],tol,n,m; struct _edge
{
int u,v,w;
}edge[maxm]; bool cmp(_edge a,_edge b)
{
return a.w<b.w;
} void addedge(int u,int v,int w)
{
edge[tol].u=u;
edge[tol].v=v;
edge[tol].w=w;
tol++;
} int _find(int x)
{
if(f[x]==-) return x;
else return f[x]=_find(f[x]);
} int kruskal()
{
M(f,-);
sort(edge,edge+tol,cmp);
int cnt=,ans=;
int u,v,w,f1,f2;
for(int i=;i<tol;i++)
{
u=edge[i].u;
v=edge[i].v;
w=edge[i].w;
f1=_find(u);
f2=_find(v);
if(f1!=f2)
{
ans+=w;
f[f1]=f2;
cnt++;
}
if(cnt==n-) break;
}
return ans;
} int main()
{
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
while(~scanf("%d%d",&n,&m)&&n)
{
tol=;
for(int i=;i<m;i++)
{
int u,v,w;
scanf("%d%d%d",&u,&v,&w);
addedge(u,v,w);
}
printf("%d\n",kruskal());
}
return ;
}