L2-024 部落

YuKiCheng發表於2024-03-19

注意merge的時候如果p1和p2相等及時返回否則死迴圈了,程式碼有問題而不是演算法超時。

#define _CRT_SECURE_NO_WARNINGS
#include <bits/stdc++.h>
using namespace std;
#define ll long long
int parent[10010], deep[10010];
int getf(int x) {
	int y = x;
	while (parent[y] != -1) {
		y = parent[y];
	}
	return y;
}
void merge(int x,int y) {
	int p1 = getf(x);
	int p2 = getf(y);
	if (p1 == p2) return;
	if (deep[p1] < deep[p2]) {
		parent[p1] = p2;
	}
	else if (deep[p1]>deep[p2]) {
		parent[p2] = p1;
	}
	else {
		parent[p1] = p2;
		deep[p2]++;
	}
}
int main() {
	memset(parent, -1, sizeof(parent));
	memset(deep, 0, sizeof(deep));
	int n;
	cin >> n;
	set<int> st;
	for (int i = 0; i < n; i++) {
		int t,tno,tno2;
		cin >> t;
		cin >> tno;
		st.insert(tno);
		for (int i = 0; i < t - 1; i++) {
			cin >> tno2;
			merge(tno, tno2);
			st.insert(tno2);
		}
	}
	int query;
	cin >> query;
	cout << st.size();
	cout << " ";
	int count = 0;
	for (auto x : st) {
		if (parent[x] == -1) count++;
	}
	cout << count << '\n';
	while (query--) {
		int a, b;
		cin >> a >> b;
		int p1 = getf(a);
		int p2 = getf(b);
		cout << (p1 == p2 ? "Y" : "N") << '\n';
	}
	return 0;
}