【bzoj 1901】树状数组套线段树

带修改区间第k大。

用树状数组维护线段树的前缀和。

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <string>
#define inf 1000000000
#define Rep(i, x, y) for (int i = x; i <= y; i ++)
#define u t[x]
#define Lc t[u.lc]
#define Rc t[u.rc]
using namespace std;
typedef long long LL;
const int N = 10005;
struct arr { int lc, rc, w; } t[N*870];
int n, a[N], m, q, tz, T[N], l1, l2, ql[N], qr[N];
void Modify(int x, int l, int r, int z) {
	u.w += z;
	if (l == r) return ;
	int mid = (l + r) / 2;
	if (q <= mid) { if (!u.lc) u.lc = ++ tz; Modify(u.lc, l, mid, z); }
	else { if (!u.rc) u.rc = ++ tz; Modify(u.rc, mid + 1, r, z); }
}
void Add(int x, int z) {
	for (; x <= n; x += x&(-x)) Modify(T[x], 0, inf, z);
}
int Qry(int l, int r) {
	if (l == r) return l;
	int mid = l + r >> 1;
	int x, z = 0;
	Rep(i, 1, l1) x = ql[i], z -= Lc.w;
	Rep(i, 1, l2) x = qr[i], z += Lc.w;
	if (q > z) {
		Rep(i, 1, l1) ql[i] = t[ ql[i] ].rc;
		Rep(i, 1, l2) qr[i] = t[ qr[i] ].rc;
		q -= z; return Qry(mid+1, r);
	} else {
		Rep(i, 1, l1) ql[i] = t[ ql[i] ].lc;
		Rep(i, 1, l2) qr[i] = t[ qr[i] ].lc;
		return Qry(l, mid);
	}
}
void Query() {
	int x, y;
	scanf ("%d%d%d", &x, &y, &q), x --, l1 = l2 = 0;
	for (; x; x -= x&(-x)) ql[++ l1] = T[x];
	for (; y; y -= y&(-y)) qr[++ l2] = T[y];
	printf ("%d\n", Qry(0, inf));
}
int main()
{
	scanf ("%d%d", &n, &m);
	Rep(i, 0, n) T[i] = ++ tz;
	Rep(i, 1, n) scanf ("%d", &a[i]), q = a[i], Add(i, 1);
	Rep(i, 1, m) {
		char ty; scanf (" %c ", &ty);
		if (ty == 'Q') Query();
		else {
			int x, y;
			scanf ("%d%d", &x, &y);
			q = a[x], Add(x, -1), q = a[x] = y, Add(x, 1);
		}
	}

    return 0;
}


发布了73 篇原创文章 · 获赞 3 · 访问量 4万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览