Kth number
Time Limit: 15000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 13656 Accepted Submission(s): 4142
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
题意:
求序列给定区间中第k小的数
主席树求区间第k小
本来想用vector 不过内存超了。。
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <vector>
#include <algorithm>
using namespace std;
#define mid ((L+R)>>1)
#define LL long long
const int N = 1e5 + 10;
int T,n,m,x,y,z,I,cnt,now,ID[N];
LL a[N],Rank[N];
struct node{
int lID,rID,sum;
node(int a,int b,int c) {lID = a; rID = b; sum = c;}
node(){lID = rID = sum = 0;}
}Sum[N*20];
void setRank(){
I = 1; sort(Rank+1,Rank+1+n);
for(int i=2;i<=n;i++) if(Rank[i]!=Rank[I]) Rank[++I] = Rank[i];
}
int getRank(LL val){
return int(lower_bound(Rank+1, Rank+1+I, val) - Rank);
}
int build(int L,int R){
if(L==R) {Sum[++cnt] = node(0,0,0); return cnt;}
int k = ++cnt;
Sum[k] = node(build(L, mid), build(mid+1, R), 0);
return k;
}
int add(int pre,int pos,int L,int R){
if(L==R) {Sum[++cnt] = node(0,0,Sum[pre].sum+1); return cnt;}
int k = ++cnt;
if(pos<=mid) Sum[k] = node(add(Sum[pre].lID, pos, L, mid),Sum[pre].rID,Sum[pre].sum+1);
else Sum[k] = node(Sum[pre].lID,add(Sum[pre].rID, pos, mid+1, R),Sum[pre].sum+1);
return k;
}
int query(int pos,int l,int r,int L,int R){
if(L==R) return L;
int l_val = Sum[Sum[r].lID].sum - Sum[Sum[l].lID].sum;
if(l_val>=pos) return query(pos, Sum[l].lID, Sum[r].lID, L, mid);
else return query(pos - l_val, Sum[l].rID, Sum[r].rID, mid+1, R);
}
void init(){
setRank();
cnt = now = 0;
build(1,I);
ID[0] = 1;
for(int i=1;i<=n;i++){
ID[i] = add(ID[i-1], getRank(a[i]), 1, I);
}
}
int main()
{
scanf("%d",&T);
while(T--){
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++) {scanf("%lld",&a[i]);Rank[i] = a[i];}
init();
while(m--){
scanf("%d%d%d",&x,&y,&z);
printf("%lld\n",Rank[query(z, ID[x-1], ID[y], 1, I)]);
}
}
return 0;
}