hdu1863-畅通工程

#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,m,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%d",&m,&n)&&m)
    {   sum=counter=0;
        FOR(i,1,m)
        {scanf("%d%d%d",&e[i].u,&e[i].v,&e[i].w);}
        sort(e+1,e+1+m,cmp);
        FOR(i,1,n)
        f[i]=i;
        FOR(i,1,m)
        {   if(merge(e[i].u,e[i].v))counter++,sum+=e[i].w;
            if(counter==n-1)break;
        }
        if(counter!=n-1){printf("?\n");continue;}
      else printf("%d\n",sum);
    }
    return 0;
}






你可能感兴趣的:(hdu1863-畅通工程)