HDU 1232 畅通工程 解题报告

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

再看完了http://acshiryu.com/archives/559这篇非常有意思的并查集入门后,发现并查集非常好用以及好入手,于是这题完全仿照

我写的代码里没有运用路径压缩这一方法。

#include<stdio.h>
#include<string.h>
int sum,pre[1000];//定义前驱数组
int find(int x)
{
    //查找根节点
    if(pre[x]!=x)
        pre[x]=find(pre[x]);
    //返回根节点
    return pre[x];

}
void join(int x,int y) //将不连通的X,Y连通起来~
{
    int fx=find(x);
    int fy=find(y);
    if(fx!=fy)
    {
        pre[fy]=fx;
        sum++;
    }
}
int main()
{
    int n,m,i;
    while(scanf("%d",&n)!=EOF&&n) //当n为0就结束
    {
        scanf("%d",&m);
        sum=0;
        for(i=1;i<=n;i++)
            pre[i]=i;
        for(i=1;i<=m;i++)
        {
            int a,b;
            scanf("%d%d",&a,&b);
            join(a,b);
        }
        printf("%d\n",n-1-sum);
    }
    return 0;
}

还有一点,大数组一般得定义在外面。

原文地址:https://www.cnblogs.com/whatthefy/p/2991103.html