1118 Birds in Forest (25 分)(并查集:计算集合个数和其成员个数)

题目链接

第一道
第二道
①统计全体个数,用map标记或set存储
②处理某个大集合的额外信息,只需要揪出其首领就好,判断条件:father[i]=i;

代码

using namespace std;
#include<bits/stdc++.h>
map<int, bool>book;
int father[10010],number[10010],cnt,num, p, q;
int findfather(int x) {
	int a = x;
	while (x != father[x])x = father[x];
	while (a != father[a]) {
		int z = a;
		a = father[a];
		father[z] = x;
	}
	return x;
}
void Union(int a, int b) {
	int fa = findfather(a);
	int fb = findfather(b);
	if (fa != fb)father[fb] =fa,    number[fa]+=number[fb],   number[fb]=0;
}
int main() {
	int n;
	cin >> n;
	for (int i = 1; i < 10000; i++)father[i] = i;
	fill(number+1, number + 10000, 1);
	for (int i = 0; i < n; i++) {
		int k,a,b;
		cin >> k;
		for (int j= 0; j < k; j++) {
			if (j == 0)cin >> a, book[a] = true;
			else {
				cin >> b, book[b] = true;
				Union(a, b);
				a = b;
			}
		}
	}
	for (auto p = book.begin(); p != book.end(); p++) {
		if (father[p->first] == p->first)cnt++;
	}
	cout << cnt << " " << book.size() << endl;
	cin >> num;
	for (int i = 0; i < num; i++) {
		cin >> p >> q;
		if (findfather(q) != findfather(p))cout << "No" << endl;
		else cout << "Yes" << endl;
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值