Kth number
Time Limit: 15000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 6217 Accepted Submission(s): 1986
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]
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
Source
划分树裸题,我也没看懂,嘿嘿!
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <algorithm>
#define maxn 100010
#define mid ((l+r)>>1)
using namespace std;
int t[20][maxn],sum[20][maxn];
int a[maxn],as[maxn];
//以下为查找区间第k小划分树
void build(int p,int l,int r)
{
int lm=0,i,ls=l,rs=mid+1;//lm表示应被放入左子树且与中位数相等的数有多少个,ls为左子树的起始位置,rs为右子树的起始位置
for(i=mid;i>=l;i--) //求lm
{
if(as[i]==as[mid])
lm++;
else
break;
}
for(i=l;i<=r;i++)
{
if(i==l)//这里要特殊讨论
sum[p][i]=0;
else
sum[p][i]=sum[p][i-1];
if(t[p][i]==as[mid])//若与中位数相等则判断是否应该被放入左子树
{
if(lm)
{
lm--;
sum[p][i]++;
t[p+1][ls++]=t[p][i];
}
else
t[p+1][rs++]=t[p][i];
}
else if(t[p][i]<as[mid])//查找区间第K大即为>
{
sum[p][i]++;
t[p+1][ls++]=t[p][i];
}
else
t[p+1][rs++]=t[p][i];
}
if(l==r)
return;
build(p+1,l,mid);
build(p+1,mid+1,r);
}
int query(int p,int l,int r,int ql,int qr,int k)
{
int s,ss;//s表示l到ql-1的区间内放入左子树的个数,ss表示区间[ql,qr]被放入左子树的个数
if(l==r)//找到所求的数
return t[p][l];
if(ql==l)
s=0,ss=sum[p][qr];
else
s=sum[p][ql-1],ss=sum[p][qr]-s;
if(k<=ss)//要找的数在左子树中
return query(p+1,l,mid,l+s,l+sum[p][qr]-1,k);
else//要找的数在右子树中
return query(p+1,mid+1,r,mid+1-l+ql-s,mid+1-l+qr-sum[p][qr],k-ss);
}
int main()
{
int t1,n,m,i,a,b,c;
cin>>t1;
while(t1--)
{
cin>>n>>m;
for(i=1;i<=n;i++)
{
cin>>as[i];
t[0][i]=as[i];
}
sort(as+1,as+n+1);
build(0,1,n);
while(m--)
{
cin>>a>>b>>c;
cout<<query(0,1,n,a,b,c)<<endl;
}
}
}