PAT题解-1118. Birds in Forest (25)-(并查集模板题)

时间:2022-08-02 21:28:17

如题。。。

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <string.h>
using namespace std;
/*
并查集水题
*/
const int maxn=+; struct UF{
int father[maxn];
void init(){
for(int i=;i<maxn;i++)
father[i]=i;
}
int find_root(int x){
if(father[x]!=x){
father[x]=find_root(father[x]);
}
return father[x];
}
void Union(int x,int y){
int fx=find_root(x);
int fy=find_root(y);
if(fx!=fy){
father[fy]=fx;
}
}
}uf;
int main()
{
int n,q;
int k,a,b;
int vis[maxn];
uf.init();
memset(vis,,sizeof(vis));
scanf("%d",&n);
for(int i=;i<n;i++){
scanf("%d %d",&k,&a);
vis[a]=;
for(int j=;j<k;j++){
scanf("%d",&b);
vis[b]=;
uf.Union(a,b);
a=b;
}
}
int flag[maxn];
memset(flag,,sizeof(flag));
int cnt=;
for(int i=;i<maxn;i++){
if(vis[i]){
cnt++;
int fa=uf.find_root(i);
flag[fa]=;
}
}
int tree=;
for(int i=;i<maxn;i++){
tree+=flag[i];
}
printf("%d %d\n",tree,cnt);
scanf("%d",&q);
for(int i=;i<q;i++){
scanf("%d %d",&a,&b);
int fa=uf.find_root(a);
int fb=uf.find_root(b);
if(fa==fb)
printf("Yes\n");
else
printf("No\n");
}
return ;
}