hdu4251The Famous ICPC Team Again【划分树入门题】

水到不能再水……

/***************
hdu4251
2016.1.28
1060MS 15816K 2320 B G++
***************/
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

const int MAXN = 1000010;
int sorted[MAXN];   //对原集合中元素排序后的值
int val[30][MAXN];  //val记录第k层当前位置的值
int toleft[30][MAXN];  //记录元素所在区间当前位置前的元素进入到左子树的个数
int sum[30][MAXN];  //记录比当前元素小的元素的和
int n;

void build(int l, int r, int d) {
    if (l == r) return ;
    int mid = (l + r) >> 1;
    int same = mid - l + 1;
    for (int i=l; i<=r; i++)
        if (val[d][i] < sorted[mid])
            same--;
    int lp = l, rp = mid+1;
    for (int i=l; i<=r; i++) {
        if (i == l) toleft[d][i] = 0;
        else toleft[d][i] = toleft[d][i-1];

        if (val[d][i] < sorted[mid]) {
            toleft[d][i]++;
            val[d+1][lp++] = val[d][i];
        } else if (val[d][i] > sorted[mid])
            val[d+1][rp++] = val[d][i];
        else {
            if (same) {
                same--;
                toleft[d][i]++;
                val[d+1][lp++] = val[d][i];
            } else val[d+1][rp++] = val[d][i];
        }
    }
    build(l, mid, d+1);
    build(mid+1, r, d+1);
}
int query(int a, int b, int k, int l, int r, int d) {
    if (a == b) return val[d][a];

    int mid = (l + r) >> 1;
    int s, ss, sss;
    if (a == l) {
        s = toleft[d][b];
        ss = 0;
    } else {
        s = toleft[d][b] - toleft[d][a-1];
        ss = toleft[d][a-1];
    }

    if (s >= k) {
        a = l + ss;
        b = l + ss + s - 1;
        return query(a, b, k, l, mid, d+1);
    } else {
        a = mid+1 + a - l - ss;
        b = mid+1 + b - l - toleft[d][b];
        return query(a, b, k-s, mid+1, r, d+1);
    }
}

int main()
{
    //freopen("cin.txt","r",stdin);
     int n, m,tot=1;
    while(~scanf("%d", &n))
    {
        printf("Case %d:\n",tot++);
        for (int i=1; i<=n; i++) {
            scanf("%d", &sorted[i]);
            val[0][i] = sorted[i];
        }
        sort(sorted+1, sorted+1+n);
        build(1, n, 0);
        int a, b, k;
        scanf("%d",&m);
        while (m--) {
            scanf("%d%d", &a, &b);
            printf("%d\n", query(a, b, (b-a)/2+1, 1, n, 0));
        }
    }
    return 0;
}


你可能感兴趣的:(数据结构,递归,ACM)