const int MAXN = 50010,MAXM = 20;
int num[MAXN],tmp[MAXN],pre[MAXN];
int ans[MAXM][MAXN],val[MAXM][MAXN];
void Init(int l,int r,int h)
{
if(l == r)
return ;
int mid = (l+r)>>1;
int i,pl,pr,sum;
for(i = l,pl = l,pr = mid+1,sum = 0;i <= r; ++i)
{
if(val[h][i] < tmp[mid] || (val[h][i] == tmp[mid] && sum < min(pre[mid],mid-l+1)))
{
val[h+1][pl++] = val[h][i],ans[h][i] = (i == l ? 1 : ans[h][i-1]+1) ;
if(val[h][i] == tmp[mid])
sum++;
}
else
val[h+1][pr++] = val[h][i],ans[h][i] = (i == l ? 0 : ans[h][i-1]);
}
Init(l,mid,h+1);
Init(mid+1,r,h+1);
}
int Query(int L,int R,int l,int r,int k,int h)
{
if(L == R)
return val[h][L];
int goleftr = ans[h][r] ;//[L,r]内被分到左边的
int goleftl = (l == L ? 0 : ans[h][l-1]);//[L,l-1]内被分到左边的
int goleft = goleftr-goleftl;//[l,r]内被分到左边的
int mid = (L+R)>>1;
int gorightr = r-L+1 - ans[h][r];//[L,r]内被分到右边的
int gorightl = l-L-goleftl;//[L,l-1]内被分到右边的
if(k <= goleft)
return Query(L,mid,L-1+goleftl+1,L-1+goleftr,k,h+1);
return Query(mid+1,R,mid+gorightl+1,mid+gorightr,k-goleft,h+1);
}
void InitKthTree(int n)
{
memcpy(tmp,num,sizeof(num));
memcpy(val[0],num,sizeof(num));
sort(tmp+1,tmp+n+1);
int i;
for(i = 2,pre[1] = 1;i <= n; ++i)
pre[i] = (tmp[i] == tmp[i-1] ? pre[i-1]+1 : 1);
Init(1,n,0);
}
允许重复数字的划分树
最新推荐文章于 2023-09-25 05:23:24 发布