给跪
题意:
给一个长为n的一维数组,查询m次,每次形式为l r k,查询从a[l]到a[r]中第k大的数是多少
Input
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 10 9 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).
The second line contains n different integer numbers not exceeding 10 9 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).
Output
For each question output the answer to it --- the k-th number in sorted a[i...j] segment.
最近码力有所下降啊,这个题虽然思路上一开始理解错了,但是真正卡住的又是实现。
线段树维护每个区间已经排好序的数组(为了节省空间,用动态空间),用二分法搜索第k大的值,每次用线段树查找l到r范围内有多少个小于当前数字的数,查找方法也是二分。如果等于k-1,则答案大于等于当前值,如果小于k-1,则答案大于当前值,如果大于k-1,则答案小于当前值。
看到评论里面一堆用splay,划分树,treap做的真是醉了,自己太弱
代码如下:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
#include<vector>
using namespace std;
#define mxn 100010
int n,m;
int a[mxn];
int inter[mxn];
class node{
public:
int ll,rr;
vector<int> num;
};
class segment_tree{
private:
node nd[mxn<<2];
void merge(int id,int ls,int rs){
int lc=0,rc=0;
int lenl=nd[ls].num.size();
int lenr=nd[rs].num.size();
while(lc!=lenl||rc!=lenr){
if(rc==lenr||lc<lenl&&nd[ls].num[lc]<nd[rs].num[rc])
nd[id].num.push_back(nd[ls].num[lc++]);
else nd[id].num.push_back(nd[rs].num[rc++]);
}
}
int bin(int l,int r,int x,int id){
int m;
int rec=l;
++r;
while(l+1<r){
m=(l+r)>>1;
if(nd[id].num[m]<x) l=m;
else r=m;
}
return nd[id].num[l]<x ? l-rec+1 : 0;
}
public:
void build(int l,int r,int id){
nd[id].num.clear();
nd[id].ll=l;
nd[id].rr=r;
if(l==r){
nd[id].num.push_back(a[l]);
return;
}
int m=(l+r)>>1,ls=id<<1,rs=ls|1;
build(l,m,ls);
build(m+1,r,rs);
merge(id,ls,rs);
}
int find(int l,int r,int x,int id){
if(nd[id].ll==l&&nd[id].rr==r){
return bin(l-nd[id].ll,r-nd[id].ll,x,id);
}
int m=(nd[id].ll+nd[id].rr)>>1,ls=id<<1,rs=ls|1;
if(r<=m) return find(l,r,x,ls);
else if(l>m) return find(l,r,x,rs);
else return find(l,m,x,ls)+find(m+1,r,x,rs);
}
}Tree;
int main(){
while(scanf("%d%d",&n,&m)!=EOF){
int minn=0x3f3f3f3f,maxx=-1;
for(int i=0;i<n;++i){
scanf("%d",&a[i]);
minn=min(a[i],minn);
maxx=max(a[i],maxx);
}
Tree.build(0,n-1,1);
int l,r,k;
for(int q=0;q<m;++q){
scanf("%d%d%d",&l,&r,&k);
--l;--r;
int lt=minn,rt=maxx+1,m;
int tem;
while(lt+1<rt){
m=(lt+rt)>>1;
tem=Tree.find(l,r,m,1);
if(tem==k-1) lt=m;
else if(tem<k-1) lt=m+1;
else rt=m;
}
printf("%d\n",lt);
}
}
return 0;
}