hdu_1863 畅通工程

#include <iostream>
#include <algorithm>
using namespace std;
int m,n;
int Father[105];
struct node
{
    int u,v,w;
};
node Edge[105];
bool cmp(node a,node b)
{
    return a.w<b.w;
}

void MakeSet()
{
    for(int i=1; i<=m; i++)
        Father[i]=i;
}
int Find(int x)
{
    while(x!=Father[x])
        x=Father[x];
    return x;
}
void Union(int x,int y)
{
    int a=Find(x);
    int b=Find(y);
    if(a!=b)
        Father[a]=b;
}
int main()
{
    int u,v,w,i,j,k,sum,Count;
    while(cin>>n>>m,n)
    {
        sum=0;
        Count=0;
        MakeSet();
        for(i=0; i<n; i++)
        {
            cin>>u>>v>>w;
            Edge[i].u=u;
            Edge[i].v=v;
            Edge[i].w=w;
        }
        sort(Edge,Edge+n,cmp);
        for(j=0; j<n; j++)
            if(Find(Edge[j].u)!=Find(Edge[j].v))
            {
                sum=sum+Edge[j].w;
                Union(Edge[j].u,Edge[j].v);
            }
            for(k=1;k<=m;k++)
                if(Father[k]!=k)
                Count++;
            if(Count==m-1)
                cout<<sum<<endl;
            else
                cout<<"?"<<endl;
    }
    return 0;
}

你可能感兴趣的:(Algorithm,HDU,Spanning,Tre,Minimun)