Codeforces 并查集题集(Disjoint Sets Union Step1)

ITMO Academy: pilot course

Disjoint Sets Union Step1

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;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

学不会数据库

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值