#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <string>
#include <map>
using namespace std;
int V,E;
const int maxn = 10000+10;
int father[maxn];
void Init()
{
for(int i = 0; i < maxn ;i++)
{
father[i] = i;
}
}
int Find(int x)
{
return father[x] == x?x:father[x] = Find(father[x]);
}
bool same(int a,int b)
{
a = Find(a);
b = Find(b);
return a==b;
}
void Union(int a , int b)
{
a=Find(a);
b=Find(b);
if(a != b) father[a] = b;
}
struct Edge
{
int from,to,cost;
} es[maxn];
bool cmp(const Edge &t1 , const Edge &t2)
{
return t1.cost < t2.cost;
}
int Krustra()
{
sort(es , es+E , cmp);
Init();
int sum = 0 ;
for(int i = 0 ;i < E;i++)
{
Edge e = es[i];
if(!same(e.from,e.to))
{
Union(e.from,e.to);
sum += e.cost;
}
}
return sum;
}
int main()
{
while(cin >> V && V)
{
cin >> E;
int from,to,cost;
int pos = 0;
for(int i = 0; i < E ; i++)
{
cin >> from >> to >> cost ;
es[i].from = from;
es[i].to= to;
es[i].cost = cost;
}
cout << Krustra() << endl;
}
return 0;
}
POJ-1287(裸的Krustra)
最新推荐文章于 2022-11-12 16:41:18 发布