HDOJ2665 Kth number --- 划分树求区间第k小数

Problem Description

Give you a sequence and ask you the kth big number of a inteval.

Input

The first line is the number of the test cases.
For each test case, the first line contain two integer n and m (n, m <= 100000), indicates the number of integers in the sequence and the number of the quaere.
The second line contains n integers, describe the sequence.
Each of following m lines contains three integers s, t, k.
[s, t] indicates the interval and k indicates the kth big number in interval [s, t]

Output

For each test case, output m lines. Each line contains the kth big number.

Sample Input




1 10 1 1 4 2 3 5 6 7 8 9 0 1 3 2

Sample Output

2

#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
// 从1开始计数
int a[22][111111];  // 保存划分树
int sorted[111111];
int num[22][111111]; // 记录进入左子树的数目
int n,m;
int l,r,k; // 每次询问的区间和

// 建树
void Build(int l,int r,int depth) {
if(l == r) {
return;  // 结束递归
}
int mid = (l + r) / 2;
int same = 0;// 记录有多少与mid的数相等且会进入左子树的元素
for(int i = l;i <= mid;i++)
if(sorted[i] == sorted[mid])
same++;
int left = l,right = mid+1;
num[depth][l] = 0;
for(int i = l;i <= r;i++) {
if(i != l) {
num[depth][i] = num[depth][i-1];
}
if(a[depth][i] < sorted[mid] || (a[depth][i] == sorted[mid] && same > 0)) {
num[depth][i]++;
a[depth+1][left++] = a[depth][i];
if(a[depth][i] == sorted[mid])
same--;
} else {
a[depth+1][right++] = a[depth][i];
}
}
Build(l,mid,depth+1);
Build(mid+1,r,depth+1);
}

// 查询区间第k小数
int Query(int l,int r,int L,int R,int k,int depth) {
if(l == r)
return a[depth][l];
int cnt;
if(l-1>=L) {
cnt = num[depth][r] - num[depth][l-1];// 区间中进入左子树的个数
}
else {
cnt = num[depth][r];// 区间中进入左子树的个数
}
int mid = (L + R) / 2;
if(k <= cnt) {
// 进入左子树查询
int newl;
if(l-1 >= L)
newl = L + (num[depth][l-1]);
else
newl = L;
int newr = newl + cnt - 1;
return Query(newl,newr ,L,mid,k,depth+1);
} else {
int newr = R - (R-r - (num[depth][R]-num[depth][r]));
int newl = newr - (r-l+1-cnt) + 1;
return Query(newl,newr,mid+1,R,k-cnt,depth+1);
}
}

int main()
{
int t;
scanf("%d",&t);
while(t--) {
scanf("%d%d",&n,&m);
for(int i = 1;i <= n;i++) {
scanf("%d",&a[1][i]);
}
for(int i = 1;i <= n;i++)
sortn ed[i] = a[1][i];
sort(sorted+1,sorted+1+n);
Build(1,n,1);
// m次问
for(int i = 0;i < m;i++) {
scanf("%d%d%d",&l,&r,&k);
printf("%d\n",Query(l,r,1,n,k,1));
}

}

return 0;
} 

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120