POJ - 1611 并查集

POJ - 1611

Severe acute respiratory syndrome (SARS), an atypical pneumonia of unknown aetiology, was recognized as a global threat in mid-March 2003. To minimize transmission to others, the best strategy is to separate the suspects from others.
In the Not-Spreading-Your-Sickness University (NSYSU), there are many student groups. Students in the same group intercommunicate with each other frequently, and a student may join several groups. To prevent the possible transmissions of SARS, the NSYSU collects the member lists of all student groups, and makes the following rule in their standard operation procedure (SOP).
Once a member in a group is a suspect, all members in the group are suspects.
However, they find that it is not easy to identify all the suspects when a student is recognized as a suspect. Your job is to write a program which finds all the suspects.

并查集三部曲:

  1. 初始化
  2. 合并
  3. 查询
#include <iostream>

using namespace std;

const int N = 40000;

int q[N];

int n, m;

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

int find(int x) {
	if (x != q[x]) {
		return find(q[x]);
	}
	return x;
}

void merge(int x, int y) {
	int a = find(x);
	int b = find(y);
	if (a != b) {
		q[a] = b;
	}
}

int main() {
	while(cin >> n >> m) {
		if (n == 0 && m == 0) {
			break;
		}
		init();  // 初始化并查集 

		for (int j = 0; j < m; j ++) {
			int k;
			cin >> k;
			int a, b;
			cin >> a;
			for (int i = 1; i < k; i ++) {
				cin >> b;
				merge(a, b);
			}
		}
		int res = 1;
		int t = find(0); // 0号的祖先 
		for (int i = 1; i <= n; i ++) {  // 统计与0号共同祖先的数量 
			if (find(i) == t) {
				res ++;
			}
		}

		cout << res << endl;
	}
	return 0;
}

优化版本

#include <iostream>

using namespace std;

const int N = 40000;

int par[N];
int ranks[N]; // 记录树的高度

int n, m;

void init() {
	for (int i = 0; i <= n; i ++) {
		par[i] = i;
		ranks[i] = 0;		
	}
}

int find(int x) {
	if (x != par[x]) {
		par[x] = find(par[x]); //路径压缩,优化
		return par[x];
	}
	return x;
}

void merge(int x, int y) {
	int a = find(x);
	int b = find(y);
	if (ranks[a] > ranks[b]) {
		par[b] = a;
	} else {
		par[a] = b;
		if (ranks[a] == ranks[b]) {
			ranks[b] ++;
		}
	}
}

int main() {
	while(cin >> n >> m) {
		if (n == 0 && m == 0) {
			break;
		}
		init();  // 初始化并查集 

		for (int j = 0; j < m; j ++) {
			int k;
			cin >> k;
			int a, b;
			cin >> a;
			for (int i = 1; i < k; i ++) {
				cin >> b;
				merge(a, b);
			}
		}
		int res = 1;
		int t = find(0); // 0号的祖先 
		for (int i = 1; i <= n; i ++) {  // 统计与0号共同祖先的数量 
			if (find(i) == t) {
				res ++;
			}
		}
		cout << res << endl;
	}
	return 0;
}

image-20230330155156813

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值