1118 Birds in Forest (25 分) (并查集
作者:互联网
#include<bits/stdc++.h>
using namespace std;
const int N=1e4+9;
int fa[N];
int find(int x){
if(x==fa[x])return fa[x];
return fa[x]=find(fa[x]);
}
void merge(int x,int y){
x=find(x),y=find(y);
if(x!=y)fa[y]=x;
}
int vis[N],cnt[N],birds,trees;
int main(){
int n;
cin>>n;
for(int i=1;i<=1e4;i++)fa[i]=i;
for(int i=1;i<=n;i++){
int k,id;
cin>>k;
if(k)cin>>id,k--;
vis[id]=1;
while(k--){
int x;
cin>>x;
merge(x,id);
vis[x]=1;
}
}
for(int i=1;i<=1e4;i++){
if(vis[i]){
int p=find(i);//先合并 然后再来一次统计当前的统计的群落
cnt[p]++;
// cout<<p<<endl;
}
}
for(int i=1;i<=1e4;i++){
if(vis[i])birds++;
if(cnt[i]){
trees++;
}
}
printf("%d %d\n",trees,birds);
int q;
cin>>q;
while(q--){
int a,b;
cin>>a>>b;
if(find(a)!=find(b)){
cout<<"No"<<endl;
}
else cout<<"Yes"<<endl;
}
return 0;
}
标签:vis,int,查集,cin,find,fa,id,1118,Birds 来源: https://blog.csdn.net/Minelois/article/details/123034587