http://codevs.cn/problem/1231/
题目描述 Description
学校需要将n台计算机连接起来,不同的2台计算机之间的连接费用可能是不同的。为了节省费用,我们考虑采用间接数据传输结束,就是一台计算机可以间接地通过其他计算机实现和另外一台计算机连接。
为了使得任意两台计算机之间都是连通的(不管是直接还是间接的),需要在若干台计算机之间用网线直接连接,现在想使得总的连接费用最省,让你编程计算这个最小的费用。
输入描述 Input Description
输入第一行为两个整数n,m(2<=n<=100000,2<=m<=100000),表示计算机总数,和可以互相建立连接的连接个数。接下来m行,每行三个整数a,b,c 表示在机器a和机器b之间建立连接的话费是c。(题目保证一定存在可行的连通方案, 数据中可能存在权值不一样的重边,但是保证没有自环)
输出描述 Output Description
输出只有一行一个整数,表示最省的总连接费用。
样例输入 Sample Input
3 3
1 2 1
1 3 2
2 3 1
样例输出 Sample Output
2
数据范围及提示 Data Size & Hint
最终答案需要用long long类型来保存
<pre name="code" class="cpp">#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<string>
#include<vector>
#include<queue>
#include<set>
#include<map>
#include<cmath>
#define mst(ss,b) memset((ss),(b),sizeof(ss))
#define maxn 0x3f3f3f3f
using namespace std;
int n,m,done=0;
int sz[100010],fa[100010];
struct node
{
int a,b,w;
}s[100010];
bool cmp(node a,node b)
{
return a.w<b.w;
}
int find(int x)
{
if(x!=fa[x])
{
fa[x]=find(fa[x]);
}
return fa[x];
}
bool Union(int a,int b)
{
a=find(a);
b=find(b);
if(a==b)
return 0;
if(sz[a]<sz[b])
swap(a,b);
fa[b]=a;
sz[a]+=sz[b];
done++;
return 1;
}
int main()
{
cin.sync_with_stdio(false);
scanf("%d%d",&n,&m);
for(int i=0;i<m;i++)
{
scanf("%d%d%d",&s[i].a,&s[i].b,&s[i].w);
}
for(int i=1;i<=n;i++)
{
sz[i]=1;
fa[i]=i;
}
sort(s,s+m,cmp);
long long ans=0;
for(int i=0;i<m;i++)
{
int a=s[i].a;
int b=s[i].b;
int w=s[i].w;
if(Union(a,b))
ans+=w;
if(done==n-1)
break;
}
//for(int i=1;i<=n;i++)
// cout<<"sz["<<i<<"]="<<sz[i]<<endl;
printf("%lld\n",ans);
return 0;
}