#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
#define MAXN 10000
#define MAXM 1000000
#define INF 1<<30
//int first[MAXN];
struct edge { int u, v, w; }a[MAXM];
bool operator<(const edge& a, const edge& b) { return a.w<b.w; }
int n, m;
int pa[MAXN]; //pa[u] 是u的直接父亲,而不是 树根 !!!
void init_set() { for(int i=0; i<n; i++) pa[i]=i; }
int find_pa(int x)
{
if(pa[x] != x) return pa[x] = find_pa(pa[x]); // pa[x] = find_pa(pa[x]) 压缩路径
else return x;
}
void Merge(int u, int v) { pa[find_pa(u)] = find_pa(v); }
int isMerge(int u, int v) { return find_pa(u) == find_pa(v); }
int exist;
int kruskal()
{
init_set(); //!!!!
int sum=0, cnt=0;
sort(a, a+m);
for(int i=0; i<m; i++)
{
int u = a[i].u, v = a[i].v;
if(!isMerge(u, v))
{
sum+=a[i].w;
cnt++;
Merge(u, v);
if(cnt == n-1) {exist=1; break; }
}
}
return sum;
}
int read_graph()
{
if(cin>>n>>m)
{
for(int i=0; i<m; i++)
cin>>a[i].u>>a[i].v>>a[i].w;
return 1;
}
return 0;
}
int main()
{
while(read_graph())
{
exist = 0;
int ans = kruskal();
cout<<(exist? ans: -1)<<endl;
}
}
转载于:https://www.cnblogs.com/tclh123/archive/2011/08/08/6171756.html