poj2104
You are working for Macrohard company in data structures department. After failing your previous task about key insertion you were asked to write a new data structure that would be able to return quickly k-th order statistics in the array segment.
That is, given an array a[1…n] of different integer numbers, your program must answer a series of questions Q(i, j, k) in the form: “What would be the k-th number in a[i…j] segment, if this segment was sorted?”
For example, consider the array a = (1, 5, 2, 6, 3, 7, 4). Let the question be Q(2, 5, 3). The segment a[2…5] is (5, 2, 6, 3). If we sort this segment, we get (2, 3, 5, 6), the third number is 5, and therefore the answer to the question is 5.
The first line of the input file contains n — the size of the array, and m — the number of questions to answer (1 <= n <= 100 000, 1 <= m <= 5 000).
The second line contains n different integer numbers not exceeding 109 by their absolute values — the array for which the answers should be given.
The following m lines contain question descriptions, each description consists of three numbers: i, j, and k (1 <= i <= j <= n, 1 <= k <= j - i + 1) and represents the question Q(i, j, k).
For each question output the answer to it — the k-th number in sorted a[i…j] segment.
7 3
1 5 2 6 3 7 4
2 5 3
4 4 1
1 7 3
5
6
3
This problem has huge input,so please use c-style input(scanf,printf),or you may got time limit exceed.
给你一个数列,多次询问区间第k大。
主席树裸题。
代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
using namespace std;
#define maxn 100100
struct node{
int w,ls,rs;
}t[maxn*20];
int a[maxn],p[maxn],b[maxn],root[maxn],n,m,x,y,k,cnt;
void built(int &x,int l,int r,int y){
t[++cnt]=t[x];
x=cnt; t[x].w++;
if(l==r)return;
int mid=(l+r)>>1;
if(y<=mid)built(t[x].ls,l,mid,y);
else built(t[x].rs,mid+1,r,y);
}
int solve(int x,int y,int l,int r,int k){
if(l==r)return a[p[l]];
int tmp=t[t[x].ls].w-t[t[y].ls].w,mid=(l+r)>>1;
if(tmp>=k)return solve(t[x].ls,t[y].ls,l,mid,k);
else return solve(t[x].rs,t[y].rs,mid+1,r,k-tmp);
}
void read(int &x){
char c=getchar();
for(;c<'0'||c>'9';c=getchar());
for(x=0;'0'<=c&&c<='9';c=getchar())x=x*10+c-'0';
}
bool cmp(int x,int y){return a[x]<a[y];}
int main(){
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)scanf("%d",&a[i]);
for(int i=1;i<=n;i++)p[i]=i;
sort(p+1,p+n+1,cmp);
for(int i=1;i<=n;i++)b[p[i]]=i;
for(int i=1;i<=n;i++)root[i]=root[i-1],built(root[i],1,n,b[i]);
for(int i=1;i<=m;i++){
scanf("%d%d%d",&x,&y,&k);
printf("%d\n",solve(root[y],root[x-1],1,n,k));
}
return 0;
}