hdu1233-还是畅通工程

#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<cstdlib>
#include<map>
#include<queue>
#include <deque>
#include <list>
#include <ctime>
#include <stack>
#include <vector>
#include<set>
#define Maxn
#define MOD
typedef long long ll;
#define FOR(i,j,n) for(int i=j;i<=n;i++)
#define DFR(i,j,k) for(int i=j;i>=k;--i)
#define lowbit(a) a&-a
#define Max(a,b) a>b?a:b
#define Min(a,b) a>b?b:a
const int inf = 0x3f3f3f3f;
const double pi = acos(-1.0);
using namespace std;
struct edge
{   int u;
    int v;
    int w;
}e[5050];
int n,f[106],sum,counter;
bool cmp(edge a,edge b)
{return a.w<b.w;}
int getf(int v)
{   if(f[v]==v)
    return v;
    else {f[v]=getf(f[v]);return f[v];}
}
int merge(int v,int u)
{   int t1,t2;
    t1=getf(v);
    t2=getf(u);
    if(t1!=t2)
    {
        f[t2]=t1;
        return 1;
    }
    return 0;
}
int main()
{   while(~scanf("%d",&n)&&n)
    {   sum=counter=0;
        FOR(i,1,n*(n-1)/2)scanf("%d%d%d",&e[i].u,&e[i].v,&e[i].w);
        sort(e+1,e+1+n*(n-1)/2,cmp);
        FOR(i,1,n)
        f[i]=i;
        FOR(i,1,n*(n-1)/2)
        {   if(merge(e[i].u,e[i].v))counter++,sum+=e[i].w;
            if(counter==n-1)break;
        }
        printf("%d\n",sum);
    }
    return 0;
}






你可能感兴趣的:(hdu1233-还是畅通工程)