【代码超详解】POJ 1611 The Suspects(并查集 + 思维)

一、题目描述

在这里插入图片描述

二、算法分析说明与代码编写指导

与 0 直接处在同一个组的,都是非典疑似患者。这些疑似患者如果同时处于别的组,那么别的组的全体成员也是非典意思患者。
这种关系可以用并查集来刻画。
我们对每个组,都令从第二个元素开始的根节点(父节点)全部指向第一个元素。
设 0 所在的组为 G,G’ 为与 G 不同的组。设 x 和 x’ 分别为 G、G’ 中的任意元素,它们的父节点分别为 f(x)、f(x’)。分两种情况完成证明:
当 G’ 在 G 后输入时,如果 x’ 在 G 中出现过,则 x’ 也算疑似感染者,并且 f(x’) = f(x) = f(0)。所以对先于 0 所在的组后输入的任意元素 x’,只要 f(x’) = f(0),则 x’ 要被记入感染总人数中。
当 G’ 在 G 前输入时,如果 x’ 后来在 G 中也出现,即 x’ = x,那么 f(x) = f(x’) = f(0)。所以对先于 0 所在的组后输入的任意元素 x’,只要 f(x’) = f(0),则 x’ 也要被记入感染总人数中。
综上:对任意的 x,只要 f(x) = f(0),则 x 要记入感染总人数。
于是我们很快可以写出代码。

三、AC 代码

#include<cstdio>
#include<algorithm>
#pragma warning(disable:4996)
using namespace std;
template<size_t n> class union_find {
private:
	unsigned root[n], rank[n];
public:
	union_find<n>() { init(); }
	union_find<n>(const bool& WannaInit) { if (WannaInit == true)init(); }
	void init() {
		fill(rank, rank + n, 1);
		for (unsigned i = 0; i < n; ++i)root[i] = i;
	}
	unsigned find_root(const unsigned& v) {
		unsigned r = v, t = v, u;
		if (t == root[v])return v;
		while (r != root[r]) { r = root[r]; }
		while (t != r) { u = root[t], root[t] = r, t = u; }
		return r;
	}
	void path_compression() { for (unsigned i = 0; i < n; ++i)find_root(i); }
	void merge(const unsigned& u, const unsigned& v) {
		unsigned fu = find_root(u), fv = find_root(v);
		if (rank[fu] <= rank[fv]) { root[fu] = fv; if (rank[fu] == rank[fv])++rank[fv]; }
		else { root[fv] = fu; }
	}
	void modify(const unsigned& u, const unsigned& v) { root[v] = u; if (rank[u] == rank[v])++rank[u]; }
	unsigned _rank(const unsigned& v) { return rank[v]; }
	size_t size() { return n; }
};
unsigned n, m, k, a, b, c = 1, f; union_find<30000> u(0);
int main() {
	for (;;) {
		u.init(); c = 1;
		scanf("%u%u", &n, &m); if (n == 0 && m == 0)return 0;
		for (unsigned h = 0; h < m; ++h) {
			scanf("%u%u", &k, &a);
			for (unsigned i = 1; i < k; ++i) { scanf("%u", &b); u.merge(a, b); }
		}
		f = u.find_root(0);
		for (unsigned i = 1; i < n; ++i)if (u.find_root(i) == f)++c;
		printf("%u\n", c);
	}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值