hdu 4251 The 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:
",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
", query(a, b, (b-a)/2+1, 1, n, 0)); } } return 0; }

좋은 웹페이지 즐겨찾기