题目链接:http://hihocoder.com/problemset/problem/1098
基本全裸最小生成树。
下面是AC代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
struct edge
{
int x,y,cost;
} ed[1000005];
int pre[100005];
int fin(int x)
{
if(x==pre[x])
{
return x;
}
else
{
return pre[x]=fin(pre[x]);
}
}
void join(int x,int y)
{
int t1=fin(x);
int t2=fin(y);
if(t1!=t2)
{
pre[t1]=t2;
}
}
bool cmp(edge a,edge b)
{
return a.cost<b.cost;
}
int main()
{
int n,m;
while(~scanf("%d%d",&n,&m))
{
for(int i=1; i<=n; i++)
{
pre[i]=i;
}
for(int i=0; i<m; i++)
{
scanf("%d%d%d",&ed[i].x,&ed[i].y,&ed[i].cost);
}
sort(ed,ed+m,cmp);
int ss=0,sum=0;
for(int i=0; i<m; i++)
{
if(fin(ed[i].x)!=fin(ed[i].y))
{
join(ed[i].x,ed[i].y);
ss++;
sum+=ed[i].cost;
}
if(ss==n-1)
{
break;
}
}
printf("%d\n",sum);
}
return 0;
}