首页 > 代码库 > hdu 2122 Ice_cream’s world III(最小生成树)

hdu 2122 Ice_cream’s world III(最小生成树)

感觉就是 畅通工程的改版 直接贴代码了

 

#include<stdio.h>#include<string.h>#include<math.h>#include<iostream>#include<algorithm>#include<queue>#include<stack>#define mem(a,b) memset(a,b,sizeof(a))#define ll __int64#define MAXN 1000#define INF 0x7ffffff#define lson l,m,rt<<1#define rson m+1,r,rt<<1|1using namespace std;struct Road{    int u,v,w;};Road r[10000+10];int fat[1000+10];int n,m,sum,ans;int cmp(Road a,Road b){    return a.w<b.w;}int find(int x){    return fat[x]==x?x:find(fat[x]);}void Kru(){    sum=1;ans=0;    for(int i=0;i<m;i++)    {        int x=find(r[i].u);        int y=find(r[i].v);        if(x!=y)        {            ans+=r[i].w;            sum++;            fat[x]=y;        }    }    if(sum==n)            printf("%d\n\n",ans);        else            printf("impossible\n\n");          }int main(){    int i,j;        while(scanf("%d%d",&n,&m)!=EOF)    {        for(i=0;i<n;i++)                    fat[i]=i;                for(i=0;i<m;i++)            scanf("%d%d%d",&r[i].u,&r[i].v,&r[i].w);                           sort(r,r+m,cmp);        Kru();    }    return 0;}