POJ 1611 The Suspects (并查集)

原题链接:The Suspects

题目大意:需要找 SARS 病毒感染者嫌疑人数,凡与感染者 0 号同学有同组关系的皆为嫌疑人。

题目分析:基础并查集应用,算是一道模版题了。将所有同属一大组的同学合并,最后找出 0 号同学所在组的人数,即为嫌疑人数。

补充:关于并查集的基本算法还不太了解的话,可以参考这篇文章:并查集算法详解


代码如下:

#include <iostream>
#include <algorithm>
using namespace std;

const int MAX = 30000;
int father[MAX], rank[MAX];

int getfather(int v) {
    if (father[v] == v)
        return v;
    else
    {
        father[v] = getfather(father[v]); //路径压缩
        return father[v];
    }
}

void judge(int x ,int y) {
    int fx = getfather(x);
    int fy = getfather(y);
    if (rank[fx] > rank[fy])
        father[fy] = fx;
    else
    {
        father[fx] = fy;
        if(rank[fx] == rank[fy])
            ++rank[fy];   //重要的是祖先的rank,所以只用修改祖先的rank就可以了,子节点的rank不用管
    }
}

void init(int n) {
    for (int i = 0; i < n; i++) {
        father[i] = i;
        rank[i] = 1;
    }
}

int main() {
    int n, m, k, first, next;
	
    while (cin >> n >> m && m + n != 0) {
        init(n);
		
        for (int i = 0; i < m; i++) {
            cin >> k >> first;
            for (int j = 1; j < k; j++) {
                cin >> next;
                judge(first, next);
                first = next;
            }
        }
		
        int ans = 0, x = getfather(0);
        for (int i = 0; i < n; i++)
            if (getfather(i) == x)   //这里不能写father[i] == x,会出错,要再更新一次根节点才行
                ans++;
				
        cout << ans << endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/laugh12321/article/details/81704862