现在的位置: 首页 > 综合 > 正文

HDOJ 1232 畅通工程

2013年10月14日 ⁄ 综合 ⁄ 共 445字 ⁄ 字号 评论关闭

http://acm.hdu.edu.cn/showproblem.php?pid=1232

题意:求最少还需要建设的道路数目。

思路:简单并查集,看还剩几个集合。

#include<stdio.h>

int set[1500];

int find(int x)
{
    while(set[x]!=x)
        x=set [x];
    return x;
}

void merge(int x,int y)
{
    x=find(x);
    y=find(y);
    if(y<x)
        set[x]=y;
    else if(y>x)
        set[y]=x;
}

main()
{
    int n,m,i,x,y,cnt;
    while(scanf("%d",&n)&&n)
    {
        scanf("%d",&m);
        for(i=1;i<=n;i++)
            set[i]=i;
        while(m>0)
        {
            scanf("%d %d",&x,&y);
            merge(x,y);
            m--;
        }
        for(cnt=-1,i=1;i<=n;i++)
            if(i==set[i])
                cnt++;
        printf("%d\n",cnt);
    }
    return 0;
}

抱歉!评论已关闭.