HDU 1233(最小生成树)

HDU 1233(最小生成树 模板)

#include <iostream>
#include <algorithm>
#include <cstdio>
using namespace std;
typedef struct
{
    int a,b;
    int v;
}node;
const int maxn=105;
int ans;
int father[maxn];
node graph[maxn*(maxn-1)/2];
int Find(int x)
{
    if(father[x]==x)
        return x;
    else
    {
        father[x]=Find(father[x]);
        return father[x];
    }
}
void Union(int x,int y,int v)
{
    if(Find(x)!=Find(y))
    {
        ans+=v;
        father[Find(x)]=Find(y);
    }
    return ;
}
bool cmp(node x,node y)
{
    if(x.v<y.v)
        return true;
    else
        return false;
}
int main()
{
    int n,m;
    while(cin>>n)
    {
        m=n*(n-1)/2;
        ans=0;
        for(int i=0;i<maxn;i++)
        {
            father[i]=i;
        }
        if(n==0)
            break;
        for(int i=0;i<m;i++)
        {
            cin>>graph[i].a>>graph[i].b>>graph[i].v;
        }
        sort(graph,graph+m,cmp);
        for(int i=0;i<m;i++)
        {
            Union(graph[i].a,graph[i].b,graph[i].v);
        }
        cout<<ans<<endl;
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/xiao-xue-di/p/9442121.html