[Zjoi2013]K大数查询 主席树+树状数组

本文介绍了一种使用树状数组套主席树解决特定问题的算法实现,并通过一道题目样例进行了说明。该方法涉及差分计算及多次前缀和求解,以高效查询区间内的第K大数值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description

有N个位置,M个操作。操作有两种,每次操作如果是1 a b c的形式表示在第a个位置到第b个位置,每个位置加入一个数c
如果是2 a b c形式,表示询问从第a个位置到第b个位置,第C大的数是多少。


Sample Input

2 5
1 1 2 1
1 1 2 2
2 1 1 2
2 1 1 1
2 1 2 3


Sample Output

1
2
1


这道题我的做法好像有点奇葩,有可能是受BZOJ3155的影响?
写了个树状数组套主席树,我是差分一下再求两次前缀和,然后求k大,好像挺模版的树套树。但我做完后栋爷过来用一波整体二分时间空间碾压我,太强了,膜一波栋爷。

#include <cstdio>
#include <cstring>

using namespace std;
typedef long long LL;

struct node {
    int lc, rc;
    LL c[2];
} t[11000000]; int cnt;
int n, m, rt[510000], ust[11000000];
bool v[510000];

void Link(int &u, int l, int r, int p, LL c, int opt) {
    if(!u) u = ++cnt;
    t[u].c[opt] += c;
    if(l == r) return ;
    int mid = l + r >> 1;
    if(p <= mid) Link(t[u].lc, l, mid, p, c, opt);
    else Link(t[u].rc, mid + 1, r, p, c, opt);
}

int lowbit(int x) {return x & -x;}
void jump(int x, int k) {
    for(int i = x; i >= 1; i -= lowbit(i)) {
        if(k == -1) ust[i] = rt[i];
        else if(k == 1 && v[i] == 0) ust[i] = t[ust[i]].lc, v[i] = 1;
        else if(v[i] == 0) ust[i] = t[ust[i]].rc, v[i] = 1;
    }
}
void change(int opt, int x, int p, int c) {
    for(int i = x; i <= n; i += lowbit(i)) 
        Link(rt[i], 0, 2 * n, p, c, opt);
}
LL getsum(int opt, int x) {
    LL ans = 0;
    for(int i = x; i >= 1; i -= lowbit(i)) 
    ans += t[t[ust[i]].rc].c[opt], v[i] = 0;
    return ans;
}

int calc(int l, int r, int ll, int rr, int k) {
    if(ll == rr) return ll;
    LL c = getsum(1, r) * LL(r + 1) - getsum(1, l) * LL(l + 1) - getsum(0, r) + getsum(0, l);
    int mid = ll + rr >> 1;
    if(k <= c) {
        jump(l, 0); jump(r, 0);
        calc(l, r, mid + 1, rr, k);
    }
    else {
        jump(l, 1); jump(r, 1);
        calc(l, r, ll, mid, k - c);
    }
}

int main() {
    scanf("%d%d", &n, &m);
    for(int i = 1; i <= m; i++) {
        int opt, x, y, c; scanf("%d%d%d%d", &opt, &x, &y, &c);
        if(opt == 1) {
            c += n;
            change(1, x, c, 1); change(1, y + 1, c, -1);
            change(0, x, c , x); change(0, y + 1, c , -y - 1);
        }
        else {
            jump(x - 1, -1); jump(y, -1);
            printf("%d\n", calc(x - 1, y, 0, 2 * n, c) - n);
        }
    }
    return 0;
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值