poj 1287 kruskal 并查集

来源:互联网 发布:linux sed 编辑:程序博客网 时间:2024/05/17 08:02

点击打开链接

//kruskal 并查集

#include <iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxv=100+5;
const int maxe=1e5;
int parent[maxv];
struct Edge{
int from,to,weight;
};
bool operator<(const Edge& E1,const Edge &E2)
{
    return E1.weight<E2.weight;
}
int v,e;
Edge edges[maxe];
int find(int x)
{
    return x==parent[x]?x:parent[x]=find(parent[x]);
}
int main()
{
    while(scanf("%d",&v)==1&&v)
    {
        scanf("%d",&e);
        for(int i=1;i<=v;i++)
            parent[i]=i;
        for(int i=0;i<e;i++)
        {
            int v1,v2,dist;
            scanf("%d%d%d",&v1,&v2,&dist);
            edges[i].from=v1;
            edges[i].to=v2;
            edges[i].weight=dist;
        }
        int sum=0;
        sort(edges,edges+e);
        for(int i=0;i<e;i++)
        {
            int p1=find(edges[i].from);
            int p2=find(edges[i].to);
            if(p1==p2) continue;
            parent[p1]=p2;
            sum+=edges[i].weight;
        }
        printf("%d\n",sum);
    }
    return 0;
}