# PAT_甲级_1118 Birds in Forest

#### 注意点

• 1、查找father的方法得使用路径压缩，不然会有一个测试点超时。

#### AC代码

``````#include<cstdio>
#include<algorithm>
#include<unordered_set>
#include<vector>

using namespace std;

unordered_set<int> birds;
unordered_set<int> trees;

int father[10005];

int findFather(int x){
int a = x;
while(x!=father[x]){
x = father[x];
}
while (a!=father[a]){
int z = father[a];
father[a] = x;
a = z;
}
return x;
}

void Union(int a,int b){
int fa = findFather(a);
int fb = findFather(b);
if(fa!=fb){
father[fa] = fb;
}
}

int main() {
for(int i=0;i<=10000;++i){
father[i] = i;
}
int n;
scanf("%d",&n);
for(int i=0;i<n;++i){
int k;
scanf("%d",&k);
vector<int> t(k);
for(int j=0;j<k;++j){
scanf("%d",&t[j]);
birds.insert(t[j]);
if(j!=0){
Union(t[j],t[j-1]);
}
}
}
for(auto it:birds){
int f=findFather(it);
trees.insert(f);
}
printf("%lu %lu\n",trees.size(),birds.size());
int query;
scanf("%d",&query);
for(int i=0;i<query;++i){
int a,b;
scanf("%d %d",&a,&b);
if(father[a]==father[b]){
printf("Yes\n");
}else{
printf("No\n");
}
}
return 0;
}
``````

566 声望
15 粉丝
0 条评论