hdu 4251 划分树

思路:裸的划分树

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cmath>
#include<cstring>
#define Maxn 100010
#define lson(x) x<<1
#define rson(x) x<<1|1
#define mid ((tree[po].l+tree[po].r)>>1)
using namespace std;
int val[][Maxn],toLeft[][Maxn],sorted[Maxn];
struct Tree{
int l,r;
}tree[Maxn*];
void BuildTree(int l,int r,int dep,int po)
{
tree[po].l=l,tree[po].r=r;
if(l==r)
return ;
int same=mid-l+,i;
for(i=l;i<=r;i++)
if(val[dep][i]<sorted[mid])
same--;
int lpos=l,rpos=mid+;
for(i=l;i<=r;i++){
if(i==l)
toLeft[dep][i]=;
else
toLeft[dep][i]=toLeft[dep][i-];
if(val[dep][i]<sorted[mid])
toLeft[dep][i]++,val[dep+][lpos++]=val[dep][i];
else
if(val[dep][i]>sorted[mid])
val[dep+][rpos++]=val[dep][i];
else
if(same)
toLeft[dep][i]++,val[dep+][lpos++]=val[dep][i],same--;
else
val[dep+][rpos++]=val[dep][i];
}
BuildTree(l,mid,dep+,lson(po));
BuildTree(mid+,r,dep+,rson(po));
}
int query(int l,int r,int k,int dep,int po)
{
if(l==r)
return val[dep][l];
int vd,invd;
if(l==tree[po].l){
vd=toLeft[dep][r];
invd=;
}
else{
vd=toLeft[dep][r]-toLeft[dep][l-];
invd=toLeft[dep][l-];
}
if(vd>=k){
int newl=invd+tree[po].l;
int newr=invd+vd+tree[po].l-;
return query(newl,newr,k,dep+,lson(po));
}
else{
int ss=l-tree[po].l-invd;
int s=r-l+-vd;
int newl=mid+ss+;
int newr=mid+ss+s;
return query(newl,newr,k-vd,dep+,rson(po));
}
}
int main()
{
int n,m,i,j,l,r,Case=,t,x;
while(scanf("%d",&n)!=EOF)
{
for(i=;i<=n;i++){
scanf("%d",val[]+i);
sorted[i]=val[][i];
}
sort(sorted+,sorted++n);
BuildTree(,n,,);
printf("Case %d:\n",++Case);
scanf("%d",&m);
for(i=;i<=m;i++){
scanf("%d%d",&l,&r);
printf("%d\n",query(l,r,(r-l+)/,,));
}
}
return ;
}
上一篇:Goodle Clean设计架构


下一篇:java 反射与其应用