天梯赛 L2-024 部落
一个并查集题目,难点就在于统计总人数,使用map即可,还有需要注意的是编号不一定是小于N的,小于10000的,需要注意。
#include<bits/stdc++.h>
using namespace std;
const int N = 10010;
int fa[N];
int find(int x){
if(x == fa[x]){
return x;
}
return fa[x] = find(fa[x]);
}
void merge(int x,int y){
int xx = find(x);
int yy = find(y);
if(xx == yy){
return;
}
fa[yy] = xx;
return;
}
int main(){
int n;
cin>>n;
for(int i = 1 ; i <= 10000 ; i++){
fa[i] = i;
}
map<int,int> cnt;
while(n--){
int k,st;
cin>>k;
cin>>st;
cnt[st]++;
for(int i = 2 ; i <= k ; i++){
int x;
cin>>x;
cnt[x]++;
merge(st,x);
}
}
cout<<cnt.size()<<" ";
map<int,int> cnt1;
for(int i = 1 ; i <= 10000 ; i++){
if(cnt[i] != 0){
cnt1[find(i)]++;
}
}
cout<<cnt1.size()<<endl;
int q;
cin>>q;
while(q--){
int x,y;
cin>>x>>y;
if(find(x) == find(y)){
cout<<"Y"<<endl;
}else{
cout<<"N"<<endl;
}
}
}