天天看点

POJ 2761 Feed the dogs 划分树

题目:http://poj.org/problem?id=2761

题意:跟POJ 2104 K-th Number一样,只是叙述不一样而已。。。

#include <iostream>  
#include <cstdio>  
#include <cstring>  
#include <algorithm>  
using namespace std;  
  
const int N = 100100;  
int n, m;  
int arr[N], arrs[N];  
int cut[20][N], seg[20][N];  
struct node  
{  
    int l, r;  
}s[N*4];  
void build(int d, int l, int r, int k)  
{  
    s[k].l = l, s[k].r = r;  
    if(l == r) return;  
    int mid = (l + r) >> 1, cnt = mid - l + 1, lb = l, rb = mid + 1;  
    for(int i = l; i <= mid; i++)  
        if(arrs[i] < arrs[mid])  
            cnt--;  
    for(int i = l; i <= r; i++)  
    {  
        if(i == l) cut[d][i] = 0;  
        else cut[d][i] = cut[d][i-1];  
        if(seg[d][i] == arrs[mid])  
        {  
            if(cnt)  
                cnt--, cut[d][i]++, seg[d+1][lb++] = seg[d][i];  
            else seg[d+1][rb++] = seg[d][i];  
        }  
        else if(seg[d][i] < arrs[mid])  
            cut[d][i]++, seg[d+1][lb++] = seg[d][i];  
        else seg[d+1][rb++] = seg[d][i];  
    }  
    build(d + 1, l, mid, k << 1);  
    build(d + 1, mid + 1, r, k << 1|1);  
}  
int query(int d, int l, int r, int k, int x)  
{  
    if(s[k].l == s[k].r)   
        return seg[d][s[k].l];  
    int ls, lss, mid = (s[k].l + s[k].r) >> 1;  
  
    if(s[k].l == l) ls = 0, lss = cut[d][r];  
    else ls = cut[d][l-1], lss = cut[d][r] - ls;  
  
    if(x <= lss) return query(d + 1, s[k].l + ls, s[k].l + ls + lss - 1, k << 1, x);  
    else return query(d + 1, mid + 1 + l - s[k].l - ls, mid + 1 + r - s[k].l - ls - lss, k << 1|1, x - lss);  
}  
int main()  
{  
    int a, b, c;  
    while(~ scanf("%d%d", &n, &m))  
    {  
        for(int i = 1; i <= n; i++)  
        {  
            scanf("%d", &arr[i]);  
            seg[0][i] = arrs[i] = arr[i];  
        }  
        sort(arrs + 1, arrs + 1 + n);  
        build(0, 1, n, 1);  
  
        while(m--)  
        {  
            scanf("%d%d%d", &a, &b, &c);  
            printf("%d\n", query(0, a, b, 1, c));  
        }  
    }  
    return 0;  
}