HDU 4417 主席树

题意:

题目链接:http://acm.split.hdu.edu.cn/showproblem.php?pid=4417
给出n个数和m个询问,询问区间[L,R]中小于等于k的数有多少。

思路:

常见的主席树思路;
但是在处理区间[L,R]的离散化时没有考了离散之后L大于R的情况,结果一直莫名其妙MLE了很久。

代码:

#include 
using namespace std;
typedef long long LL;
const int MAXN = 1e5 + 10;

struct node {
    int ls, rs, sum;
} ns[MAXN * 20];

int ct;
int rt[MAXN * 20];
int a[MAXN], b[MAXN];

void cpy(int& now, int old) {
    now = ++ct;
    ns[now] = ns[old];
}

void pushUp(int now) {
    ns[now].sum = ns[ns[now].ls].sum + ns[ns[now].rs].sum;
}

void build(int& now, int l, int r) {
    now = ++ct;
    ns[now].sum = 0;
    if (l == r) return;
    int m = (l + r) >> 1;
    build(ns[now].ls, l, m);
    build(ns[now].rs, m + 1, r);
}

void update(int& now, int old, int l, int r, int x) {
    cpy(now, old);
    if (l == r) {
        ns[now].sum++;
        return;
    }
    int m = (l + r) >> 1;
    if (x <= m) update(ns[now].ls, ns[old].ls, l, m, x);
    else update(ns[now].rs, ns[old].rs, m + 1, r, x);
    pushUp(now);
}


int query(int now, int old, int l, int r, int L, int R) {
    if (L <= l && r <= R) return ns[now].sum - ns[old].sum;
    int m = (l + r) >> 1, res = 0;
    if (L <= m) res += query(ns[now].ls, ns[old].ls, l, m, L, R);
    if (R > m) res += query(ns[now].rs, ns[old].rs, m + 1, r, L, R);
    return res;
}

int main() {
    //freopen("in.txt", "r", stdin);
    int T, cs = 0;
    scanf("%d", &T);
    while (T--) {
        int n, m;
        scanf("%d%d", &n, &m);
        for (int i = 1; i <= n; i++) {
            scanf("%d", &a[i]);
            b[i] = a[i];
        }
        sort (b + 1, b + 1 + n);
        int sz = unique(b + 1, b + 1 + n) - b - 1;
        ct = 0;
        build(rt[0], 1, sz);
        for (int i = 1; i <= n; i++) {
            a[i] = lower_bound(b + 1, b + 1 + sz, a[i]) - b;
            //cout << a[i] << endl;
            update(rt[i], rt[i - 1], 1, sz, a[i]);
        }
        printf("Case %d:\n", ++cs);
        while (m--) {
            int L, R, k;
            scanf("%d%d%d", &L, &R, &k);
            ++L; ++R;
            int KB = lower_bound(b + 1, b + 1 + sz, k) - b;
            if (KB > sz || b[KB] > k) --KB;
            if (KB < 1) printf("0\n");
            else printf("%d\n", query(rt[R], rt[L - 1], 1, sz, 1, KB));
        }
    }
    return 0;
}

你可能感兴趣的:(主席树)