poj 2104 划分树

思路:裸的划分树

#include<iostream>

#include<algorithm>

#include<cstring>

#include<cstdio>

#include<vector>

#define Maxn 100010

#define lson(x) x<<1

#define rson(x) x<<1|1

using namespace std;

int n,m,val[20][Maxn],toLeft[20][Maxn],sorted[Maxn];

struct Tree{

    int l,r;

    int mid(){

        return (l+r)>>1;

    }

}tree[Maxn*4];

void BuildTree(int l,int r,int dep,int po)

{

    tree[po].l=l,tree[po].r=r;

    if(l==r)

        return ;

    int mid=tree[po].mid();

    int lpos=l,rpos=mid+1;

    int same=mid-l+1,i;

    for(i=l;i<=r;i++){

        if(val[dep][i]<sorted[mid])

            same--;

    }

    for(i=l;i<=r;i++){

        if(i==l) toLeft[dep][i]=0;

        else toLeft[dep][i]=toLeft[dep][i-1];

        if(val[dep][i]<sorted[mid]){

            val[dep+1][lpos++]=val[dep][i],toLeft[dep][i]++;

        }

        else

        if(val[dep][i]>sorted[mid]){

            val[dep+1][rpos++]=val[dep][i];

        }

        else

        if(same){

            val[dep+1][lpos++]=val[dep][i],toLeft[dep][i]++,same--;

        }

        else

            val[dep+1][rpos++]=val[dep][i];

    }

    BuildTree(l,mid,dep+1,lson(po));

    BuildTree(mid+1,r,dep+1,rson(po));

}

int query(int l,int r,int k,int dep,int po)

{

    //cout<<tree[po].l<<" "<<tree[po].r<<endl;

    if(l==r)

        return val[dep][l];

    int ls,lns;

    if(l==tree[po].l){

        ls=toLeft[dep][r];

        lns=0;

    }else{

        ls=toLeft[dep][r]-toLeft[dep][l-1];

        lns=toLeft[dep][l-1];

    }

    int mid=tree[po].mid();

    if(ls>=k){

        int newl=tree[po].l+lns;

        int newr=tree[po].l+lns+ls-1;

        return query(newl,newr,k,dep+1,lson(po));

    }

    else{

        int rns=l-tree[po].l-lns;

        int rs=r-l+1-ls;

        int newl=mid+1+rns;

        int newr=mid+rns+rs;

        return query(newl,newr,k-ls,dep+1,rson(po));

    }

}

int main()

{

    int i,j,a,b,k;

    while(scanf("%d%d",&n,&m)!=EOF)

    {

        for(i=1;i<=n;i++){

            scanf("%d",&val[0][i]);

            sorted[i]=val[0][i];

        }

        sort(sorted+1,sorted+1+n);

        BuildTree(1,n,0,1);

        for(i=0;i<m;i++){

            scanf("%d%d%d",&a,&b,&k);

            printf("%d\n",query(a,b,k,0,1));

        }

    }

    return 0;

}

 

你可能感兴趣的:(poj)