HDU 4417 划分树+二分

#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstdio>
using namespace std;
#define manx 100009
int x[manx],tree[20][manx],sum_left[20][manx];

void make(int level,int left,int right){
    if(left==right) return ; 
    int mid = (left+right)>>1;
    int num = mid - left + 1;
    for(int i=left;i<=right;i++){
        if(tree[level][i]<x[mid])
        	num--;
    }
    int lpos = left, rpos = mid+1;
    for(int i=left; i<=right; i++){
        if(i==left) sum_left[level][i]=0;
        else sum_left[level][i]=sum_left[level][i-1];
        if(tree[level][i]<x[mid]){
            sum_left[level][i]++;
            tree[level+1][lpos++] = tree[level][i];    
        }
        else if(tree[level][i]>x[mid])
            tree[level+1][rpos++] = tree[level][i];
        else {
            if(num > 0){
                num--;
                sum_left[level][i]++;
                tree[level+1][lpos++]=tree[level][i];
            }
            else tree[level+1][rpos++]=tree[level][i]; 
        }
    }
    make(level+1,left,mid);
    make(level+1,mid+1,right);
}

int query(int level,int left,int right,int l,int r,int k){
    if(l==r) return tree[level][l];
    int s, ss, mid = (left+right)>>1;
    if(left==l){
        s = 0;
        ss = sum_left[level][r];
    }
    else {
        s = sum_left[level][l-1];
        ss = sum_left[level][r]-s;
    }
    int newl,newr;
    if(k<=ss){
        newl = left + s;
        newr = left + s + ss - 1;
        return query(level+1,left,mid,newl,newr,k);
    }
    else {
        newl = mid + (l-left-s+1);
        newr = mid + (r-left-s-ss+1);
        return query(level+1,mid+1,right,newl,newr,k-ss);
    }
} 

int main(){
    int n,q,ca=0;
    int t;
    scanf("%d",&t);
    while(t--){
    	scanf("%d%d",&n,&q);
        for(int i=1;i<=n;i++){
            scanf("%d",&tree[0][i]);
            x[i] = tree[0][i];
        }
        sort(x+1,x+n+1);
        make(0,1,n);
        printf("Case %d:\n",++ca);
        while(q--){
            int l,r,k;
            scanf("%d%d%d",&l,&r,&k);
            l++, r++;
            int mid,left=1,right=r-l+1,ans=0;;
            while(left<=right){
                mid = (left+right)>>1;
                if(query(0,1,n,l,r,mid)>k) right=mid-1;
                else {
                    ans = mid; 
                    left = mid+1;
                }
            }               
            printf("%d\n",ans);
        }
    }
} 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值