[zjoi2013]k大数查询

#include <cstdio>

#include <cstdlib>

#include <cmath>

#include <cstring>

#include <ctime>

#include <algorithm>

   

#define REP(i, n) for (i = 0; i < (n); ++i)

#define int64 long long

#define oo 0x13131313

#define maxn 50005

#define Max(a, b) (a > b ? a : b)

#define Min(a, b) (a < b ? a : b)

   

using namespace std;

   

struct node { int s, t; node *c[2]; } null[maxn * 100], *nt = null;

struct seg { node *R; seg *c[2]; } ss[maxn * 2], *st = ss, *root;

int n, m, L, R;

   

void modify(node *&p, int l, int r)

{

    if (!p || p == null) p = ++nt, p->c[0] = p->c[1] = null;

    if (L <= l && r <= R) { p->s += r - l + 1, ++p->t; return; }

    int mid = (l + r) >> 1;

    if (L <= mid) modify(p->c[0], l, mid);

    if (R > mid) modify(p->c[1], mid + 1, r);

    p->s += Min(R, r) - Max(L, l) + 1;

}

   

int ask(node *p, int l, int r)

{

    if (!p || p == null) return 0;

    if (L <= l && r <= R) return p->s;

    int res = 0, mid = (l + r) >> 1;

    if (L <= mid) res += ask(p->c[0], l, mid);

    if (R > mid) res += ask(p->c[1], mid + 1, r);

    return res + p->t * (Min(R, r) - Max(L, l) + 1);

}

   

void build(seg *p, int l, int r)

{

    if (l == r) return;

    build(p->c[0] = ++st, l, (l + r) >> 1);

    build(p->c[1] = ++st, ((l + r) >> 1) + 1, r);

}

   

void modify(int a, int b, int c)

{

    int l = 1, r = n; seg *p = root; L = a, R = b;

    for (; modify(p->R, 1, n), l < r; )

        p = c > (l + r) >> 1 ?

            (l = ((l + r) >> 1) + 1, p->c[1]) : (r = (l + r) >> 1, p->c[0]);

}

   

int ask(int a, int b, int c)

{

    int l = 1, r = n; seg *p = root; L = a, R = b;

    for (; l < r; ) {

        int k = ask(p->c[1]->R, 1, n);

        p = k < c ? (r = (l + r) >> 1, c -= k, p->c[0]) : (l = ((l + r) >> 1) + 1, p->c[1]);

    }

    return l;

}

   

int main()

{

    freopen("sequence.in", "r", stdin);

    freopen("sequence.out", "w", stdout);

   

    scanf("%d%d", &n, &m);

    build(root = ++st, 1, n);

    for (; m--; ) {

        int t, a, b, c;

        scanf("%d%d%d%d", &t, &a, &b, &c);

        t == 1 ? modify(a, b, c), 1 : printf("%d\n", ask(a, b, c));

    }

}


你可能感兴趣的:(查询)