PTA甲级考试真题练习118——1118 Birds in Forest

题目

PTA甲级考试真题练习118——1118 Birds in Forest_第1张图片

思路

并查集

代码

#include 
#include 
#include 
using namespace std;
const int nmax = 10010;
vector<int> father;
int find(int i) {
     
	int j = i;
	while (father[j] >= 0)  j = father[j];
	int t;
	for (int k = i; k != j; k = t) {
     
		t = father[k];
		father[k] = j;
	}
	return j;
}
void merge(int r1, int r2) {
     
	int i = find(r1);
	int j = find(r2);
	if (i != j) {
     
		if (father[i] > father[j]) {
     
			father[j] += father[i];
			father[i] = j;
		}
		else {
     
			father[i] += father[j];
			father[j] = i;
		}
	}
}
int main()
{
     
	int n;
	cin >> n;
	father.resize(nmax);
	fill(father.begin() + 1, father.begin() + nmax, -1);
	int maxn = 0;
	for (int i = 0; i < n; ++i) {
     
		int num; cin >> num;
		if (num == 1) {
     
			int cur; cin >> cur;
			maxn = max(cur, maxn);
		}
		if (num > 1) {
     
			int cur; cin >> cur;
			maxn = max(cur, maxn);
			for (int j = 1; j < num; ++j) {
     
				int tmp; cin >> tmp;
				maxn = max(tmp, maxn);
				merge(cur, tmp);
			}
		}
	}
	int sum = 0;
	for (int i = 1; i <= maxn; ++i) {
     
		if (father[i] <= 0)
			sum++;
	}
	cout << sum<<" "<<maxn<<endl;
	int qn; cin >> qn;
	int first, second;
	for (int i = 0; i < qn; ++i) {
     
		cin >> first >> second;
		if (find(first) == find(second))
			cout << "Yes" << endl;
		else
			cout << "No" << endl;
	}
}

你可能感兴趣的:(PAT甲级考试真题练习)