1118. Birds in Forest
Hash会误将这个当成两棵树,而出现问题。
例如:
① 1 2 3
② 4 5 6
③ 3 7 4
#include<iostream>
#include<set>
using namespace std;
const int maxn = 10010;
set<int> st;
int n, m, k;
int fa[maxn], cnt[maxn];
int findFather(int x) {
int a = x;
while(x != fa[x])
x = fa[x];
while(a != fa[a]) {
int z = a;
a = fa[a];
fa[z] = x;
}
return x;
}
void Union(int a, int b) {
int faA = findFather(a);
int faB = findFather(b);
if(faA != faB) fa[faA] = faB;
}
bool exist[maxn];
int main() {
scanf("%d", &n);
for(int i = 1; i <= maxn; i++) fa[i] = i;
int id, temp;
for(int i = 0; i < n; i++) {
scanf("%d%d", &k, &id);
exist[id] = true;
for(int j = 0; j < k-1; j++) {
scanf("%d", &temp);
Union(id, temp);
exist[temp] = true;
}
}
int numBirds = 0;
for(int i = 1; i <= maxn; i++) {
if(exist[i] == true) {
numBirds++;
int q=findFather(i);
st.insert(q);
}
}
printf("%d %d\n", st.size(), numBirds);
scanf("%d", &m);
int x, y;
for(int i = 0; i < m; i++) {
scanf("%d%d", &x, &y);
printf("%s\n", (findFather(x) == findFather(y)) ? "Yes" : "No");
}
return 0;
}