分析:PAT日常之并查集,递归findF返回是father[x]而不是x,注意最后的father[]数组不是最终每个结点的father,因此还要通过findF找其father,不过判断并查集个数可以直接用i == father[i]判断
#include<stdio.h>
int father[(int)1e4+7];
void init(){
int i, len = (int)1e4+7;
for(i = 1; i<len; i++)
father[i] = i;
}
int findF(int x){
if(x != father[x]) father[x] = findF(father[x]);
return father[x];
}
void join(int a, int b){
int fa = findF(a);
int fb = findF(b);
if(fa != fb) father[fb] = fa;
}
int main(){
//freopen("in.txt", "r", stdin);
int n, k, q, i, j, num1, num, treenum = 0, maxn = 0;
scanf("%d", &n);
init();
for(i = 0; i<n; i++){
scanf("%d %d", &k, &num1);
if(num1 > maxn) maxn = num1;
for(j = 1; j<k; j++){
scanf("%d", &num);
if(num > maxn) maxn = num;
join(num1, num);
}
}
for(i = 1; i<=maxn; i++)
if(i == father[i]) treenum++;
printf("%d %d\n", treenum, maxn);
scanf("%d", &q);
for(i = 0; i<q; i++){
scanf("%d %d", &num, &num1);
if(findF(num) == findF(num1)) printf("Yes\n");
else printf("No\n");
}
return 0;
}