A. Disjoint Sets Union
思路:并查集模板 1 1 1
Code:
#include <bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
typedef long long ll;
typedef pair<int,int> PII;
const int N=1e5+10,mod=1e9+7;
int n,m,fa[N],u,v;
string s;
int get(int x){
if(x==fa[x]) return x;
return fa[x]=get(fa[x]);
}
void merge(int x,int y){
int fx=get(x),fy=get(y);
fa[fy]=fx;
}
int main(){
IOS;
cin>>n>>m;
for(int i=1;i<=n;i++) fa[i]=i;
while(m--){
cin>>s>>u>>v;
if(s=="union") merge(u,v);
else{
if(get(u)==get(v)){
cout<<"YES"<<endl;
}else{
cout<<"NO"<<endl;
}
}
}
return 0;
}
B. Disjoint Sets Union 2
思路:并查集模板
2
2
2,求出一个节点所在集合的最大值、最小值、集合大小
在
m
e
r
g
e
merge
merge函数里维护三个数组
m
a
n
x
manx
manx、
m
i
n
x
minx
minx、
c
n
t
cnt
cnt即可
C o d e : Code: Code:
#include <bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
typedef long long ll;
typedef pair<int,int> PII;
const int N=3e5+10,mod=1e9+7;
int n,m,fa[N],u,v,manx[N],minx[N],cnt[N];
string s;
void init(){
for(int i=1;i<=n;i++) {
fa[i]=manx[i]=minx[i]=i;
cnt[i]=1;
}
}
int find(int x){
if(x==fa[x]) return x;
return fa[x]=find(fa[x]);
}
void merge(int x,int y){
int fx=find(x),fy=find(y);
if(fx==fy) return ;
fa[fy]=fx;
manx[fx]=manx[fy]=max(manx[fx],manx[fy]);
minx[fx]=minx[fy]=min(minx[fx],minx[fy]);
cnt[fx]+=cnt[fy],cnt[fy]+=cnt[fx];
}
int main(){
IOS;
cin>>n>>m;
init();
while(m--){
cin>>s>>u;
if(s=="union"){
cin>>v;
merge(u,v);
}else{
cout<<minx[find(u)]<<" "<<manx[find(u)]<<" "<<cnt[find(u)]<<endl;
}
}
return 0;
}