并查集之冗余关系

计蒜课网站上课程《程序设计竞赛入门》提到并查集思想,结合了次博主http://blog.csdn.net/dellaserss/article/details/7724401详细的解答,我终于写了第一道有关于并查集的程序。

此题目选自   http://www.jisuanke.com/course/8/364


#include
#include
int fa[2000];
// father函数返回的是节点x的祖先节点
int father(int x) {
    if (fa[x] != x) fa[x] = father(fa[x]);
    return fa[x];
}
// 合并两个节点所在集合,同时判断两个点之前是否在一个集合里
// 函数返回true则之前两个点不在一个集合中
bool join(int x, int y) {
    int fx = father(x), fy = father(y);
    if (fx != fy) {
        fa[fx] = fy;
        return true;
    } else {
        return false;
    }
}

int main()
{
    void init(int );
    int n,m,ans;
    while(~scanf("%d %d",&n,&m) && n+m)
    {
        ans = 0;
        int a,b;
        init(n);
        for(int i =1;i<=n;i++)
        {
            scanf("%d %d",&a,&b);
            if(join(a,b));
            else ans++;
        }
        printf("%d\n",ans);
    }
}

void init(int n) {
    for (int i = 1; i <= n; ++i) fa[i] = i;
}
第一次写博客,不喜勿喷,谢谢。



你可能感兴趣的:(并查集)