一道并查集的题
//ccf 201412-4 最优灌溉 比较困难的一道并查集 已过
#include<iostream>
#include<algorithm>
using namespace std;
int pre[100000];
struct Node{
int first;
int end;
int val;
};
int find(int x)
{
while(pre[x]!=x)
{
x=pre[x];
}
return x;
}
int join(int x,int y)
{
int fx,fy;
fx=find(x);
fy=find(y);
if(fx==fy)
return 0;
pre[fx]=fy;
//cout<<"r";
return 1;
}
int com(Node a,Node b)
{
return a.val<b.val;
}
int main()
{
int n,m;
int sum=0;
cin>>n>>m;
Node node[m];
for(int i=0;i<100000;i++)
pre[i]=i;
for(int i=0;i<m;i++)
{
cin>>node[i].first>>node[i].end>>node[i].val;
}
sort(node,node+m,com);//不需要m-1
for(int i=0;i<m;i++)
{
int t=0;
t=join(node[i].first,node[i].end);
//cout<<join(node[i].first,node[i].end);
if(t)
{
sum+=node[i].val;
}
}
cout<<sum;
return 0;
}