POJ-1287(裸的Krustra)

来源:互联网 发布:蒙古作文软件 编辑:程序博客网 时间:2024/06/06 02:44
#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;}

原创粉丝点击