1118 Birds in Forest (25 分)

Some scientists took pictures of thousands of birds in a forest. Assume that all the birds appear in the same picture belong to the same tree. You are supposed to help the scientists to count the maximum number of trees in the forest, and for any pair of birds, tell if they are on the same tree.

Input Specification:
Each input file contains one test case. For each case, the first line contains a positive number N (≤10
​4
​​ ) which is the number of pictures. Then N lines follow, each describes a picture in the format:

K B
​1
​​ B
​2
​​ … B
​K
​​

where K is the number of birds in this picture, and B
​i
​​ 's are the indices of birds. It is guaranteed that the birds in all the pictures are numbered continuously from 1 to some number that is no more than 10
​4
​​ .

After the pictures there is a positive number Q (≤10
​4
​​ ) which is the number of queries. Then Q lines follow, each contains the indices of two birds.

Output Specification:
For each test case, first output in a line the maximum possible number of trees and the number of birds. Then for each query, print in a line Yes if the two birds belong to the same tree, or No if not.

Sample Input:
4
3 10 1 2
2 3 4
4 1 5 7 8
3 9 6 4
2
10 5
3 7
Sample Output:
2 10
Yes
No

并查集+压缩路径,硬算的话应该是过不了的

但是考虑到数据规模的问题,我其实一开始并不想用一个max_来统计鸟的数量,一开始用的是map<int,int>那么我的树木数量就是map中value为0 的数量,鸟的数量应该就是map的size,但是很可惜有两个测试点通不过,希望知道的人能告诉我一下为什么。

#include<bits/stdc++.h>
using namespace std;
int find_(int x, vector<int>& parent) {
	return parent[x] == -1 ? x : find_(parent[x], parent);
}
void union_(int x, int y, vector<int>& parent, vector<int>& rank) {
	int x_root = find_(x, parent);
	int y_root = find_(y, parent);
	if (x_root == y_root)
		return;
	if (rank[x_root] > rank[y_root])
		parent[y_root] = x_root;
	else if (rank[x_root] < rank[y_root])
		parent[x_root] = y_root;
	else{
		rank[y_root]++;
		parent[x_root] = y_root;
	}
}
int main()
{
	int n, m, max_ = -1, b, a;
	cin >> n;
	vector<int>parent(1e5, -1), rank(1e5, 0);
	for (int i = 0; i < n; i++) {
		cin >> m;
		m--;
		cin >> a;
		max_ = max(max_, a);
		while (m--) {
			cin >> b;
			union_(a, b, parent, rank);
			max_ = max(max_, b);
		}
	}
	cout << count(parent.begin() + 1, parent.begin() + max_ + 1, -1) << " " << max_ << endl;
	cin >> n;
	while (cin >> b >> m)
		if (find_(b, parent) == find_(m, parent))
			cout << "Yes" << endl;
		else
			cout << "No" << endl;
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值