n个数,m次操作,M是合并,Q是查询是否在一个集合
输入:
4 5
M 1 2
M 3 4
Q 1 2
Q 1 3
Q 3 4
输出:
Yes
No
Yes
#include<bits/stdc++.h>
using namespace std;
int n,m;
struct DSU{
vector<int> f,siz;
DSU(){}
DSU(int n){
init(n);
}
void init(int n){
f.resize(n);
iota(f.begin(),f.end(),0);
siz.assign(n,1);
}
int find(int x){
while(x!=f[x])x=f[x]=f[f[x]];
return x;
}
bool same(int x,int y){
return find(x)==find(y);
}
bool merge(int x,int y){
x=find(x),y=find(y);
if(x==y)return false;
siz[x]+=siz[y];
f[y]=x;
return true;
}
int size(int x){
return siz[find(x)];
}
};
int main(){
cin>>n>>m;
DSU dsu(n+10);
while(m--){
char op;
int a,b;
cin>>op>>a>>b;
if(op=='M')dsu.merge(a,b);
else{
if(dsu.same(a,b))cout<<"Yes"<<endl;
else cout<<"No"<<endl;
}
}
return 0;
}