首页 > 代码库 > hdu1863(最小生成树)

hdu1863(最小生成树)

很裸的最小生成树,但要注意判断输出问号的情况。其实就是当给的图不是连通图时输出问号。判断方法是:看形成的最小生成树的边数是不是等于节点数减一。

#include<iostream>#include<cstdio>#include<cstdlib>#include<cstring>#include<cmath>#include<map>#include<set>#include<vector>#include<algorithm>#include<stack>#include<queue>using namespace std;#define INF 1000000000#define eps 1e-8#define pii pair<int,int>#define LL long long intint n,m,p[105],num;LL ans;struct node{    int u,v;    LL w;} e[10010];bool cmp(node aa,node bb){    return aa.w<bb.w;}int finds(int x){    return p[x]==x?x:p[x]=finds(p[x]);}int main(){   // freopen("in1.txt","r",stdin);    //freopen("out.txt","w",stdout);    while(scanf("%d%d",&n,&m)==2)    {        if(n==0) break;        ans=0;        num=0;        for(int i=0; i<n; i++)        {            scanf("%d%d%I64d",&e[i].u,&e[i].v,&e[i].w);        }        for(int i=1; i<=m; i++)        {            p[i]=i;        }        sort(e,e+n,cmp);        for(int i=0; i<n; i++)        {            int x=finds(e[i].u);            int y=finds(e[i].v);            if(x!=y)            {                ans+=e[i].w;                num++;                p[x]=y;            }        }        if(num==m-1)            printf("%I64d\n",ans);        else            printf("?\n");    }    //fclose(stdin);    //fclose(stdout);    return 0;}