【并查集 && 合并x~y】CodeForces 566D Restructuring Company

Step1 Problem:

n 个人,初始每个人都属于自己的部门,q 次操作
三种操作:
1 :x 所在部门和 y 所在部门合并
2 :合并 x, x+1, ….. y-1, y(也就是合并 x 到 y 全部)的部门
3 :询问 x, y 是否属于同一个部门
数据范围:
1<=n<=200000, 1<=q<=500000.

Step2 Ideas:

核心需要解决 2 操作:
如果对于每次询问都直接合并,O(n*q) 肯定超时,对于每次新的询问,有很多人已经在同一个部门了。
所以我们可以记录每个人右边哪个人可能不是同一个部门,这样中间过程的人,就没必要再合并了。

Step3 Code:

#include<bits/stdc++.h>
using namespace std;
const int N = 2e5+5;
int f[N], n, nex[N];
void init()
{
    for(int i = 0; i <= n; i++)
        f[i] = i, nex[i] = i;
}
int Find(int x)
{
    if(x == f[x]) return x;
    else return f[x] = Find(f[x]);
}
void Merge(int x, int y)
{
    x = Find(x); y = Find(y);
    if(x != y) f[y] = x;
}
int main()
{
    int q;
    scanf("%d %d", &n, &q);
    init();
    int op, x, y;
    while(q--)
    {
        scanf("%d %d %d", &op, &x, &y);
        if(op == 1) Merge(x, y);
        else if(op == 2) {
            int to;
            for(int i = x; nex[i]+1 <= y; i = to)
            {
                to = nex[i]+1;
                Merge(to, i);
                nex[i] = y;
            }
        }
        else {
            if(Find(x) == Find(y)) printf("YES\n");
            else printf("NO\n");
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值