【可持久化线段树】【主席树】[HDU4417]Super Mario

来源:互联网 发布:网络运营商有哪些 编辑:程序博客网 时间:2024/05/01 23:32

Mario is world-famous plumber. His “burly” figure and amazing jumping ability reminded in our memory. Now the poor princess is in trouble again and Mario needs to save his lover. We regard the road to the boss’s castle as a line (the length is n), on every integer point i there is a brick on height hi. Now the question is how many bricks in [L, R] Mario can hit if the maximal height he can jump is H.

裸的模板题目,就是询问区间第K小这里注意一下数组是从0开始的就行了

#include <cstdio>#include <cstring>#include <algorithm>#include <iostream>using namespace std;const int MAXN = 1e5+10;struct Tree{    int ch[2];    int sum;}pool[MAXN*40+10];int queries[MAXN+10][3], uniq[MAXN*2+10], val[MAXN+10], tot, n, m, Len, roots[MAXN+10];void Insert(int &u, int l, int r, int v){    ++tot;    pool[tot] = pool[u];    u = tot;    pool[u].sum ++;    if(l == r) return ;    int mid = (l + r) >> 1;    if(v <= mid) Insert(pool[u].ch[0], l, mid, v);    else Insert(pool[u].ch[1], mid+1, r, v);}int Query(int a, int b, int l, int r, int H){    if(r <= H) return pool[b].sum - pool[a].sum;    if(l > H) return 0;    int mid = (l + r) >> 1;    return Query(pool[a].ch[0], pool[b].ch[0], l, mid, H) + Query(pool[a].ch[1], pool[b].ch[1], mid+1, r, H);}void Init(){    while(tot){        pool[tot].ch[0] = pool[tot].ch[1] = pool[tot].sum = 0;        tot--;    }}void Read(){    int tmp=0;    scanf("%d%d", &n, &m);    for(int i=1;i<=n;i++){        scanf("%d", &val[i]);        uniq[++tmp] = val[i];    }    for(int i=1;i<=m;i++){        scanf("%d%d%d", &queries[i][0], &queries[i][1], &queries[i][2]);        uniq[++tmp] = queries[i][2];    }    sort(uniq+1, uniq+1+tmp);    Len = unique(uniq+1, uniq+1+tmp) - uniq - 1;    for(int i=1;i<=n;i++)        val[i] = lower_bound(uniq+1, uniq+1+Len, val[i]) - uniq;    for(int i=1;i<=m;i++)        queries[i][2] = lower_bound(uniq+1, uniq+1+Len, queries[i][2]) - uniq;}void Solve(){    for(int i=1;i<=n;i++){        roots[i] = roots[i-1];        Insert(roots[i], 1, Len, val[i]);    }    for(int i=1;i<=m;i++)        printf("%d\n", Query(roots[queries[i][0]], roots[queries[i][1]+1], 1, Len, queries[i][2]));}int main(){    int T, t=0;    scanf("%d", &T);    while(t<T){        printf("Case %d:\n", ++t);        Init();        Read();        Solve();    }    return 0;}


0 0
原创粉丝点击