【POJ2104】区间第k大
Description
给定一个长度为n的序列,m个询问,每个询问的形式为:L,r,k表示在[L,r]间中的第k大元素。
Input
第1行:2个数,n,m表示序列的长度和询问的个数
第2行:n个数,表示n个数的大小
第3-m+2行:每行3个数,L,r,k表示询问在[L,r]区间内第k小的元素
第2行:n个数,表示n个数的大小
第3-m+2行:每行3个数,L,r,k表示询问在[L,r]区间内第k小的元素
Output
对于每个询问,输出答案。
Sample Input
7 2
1 5 2 6 3 7 4
1 5 3
2 7 1
Sample Output
3
2
Hint
【数据范围】
对于100%的数据,n<=100000, m<=100000,1<=L<=r<=n, 1<=k<=r-L+1
对于100%的数据,n<=100000, m<=100000,1<=L<=r<=n, 1<=k<=r-L+1
Solution
这个……题意就不用概括了。
区间第K大有多种模板去解决,现在我们来试一下树套树解决。
存在区间和排名,所以我么很容易想到的是线段树套平衡树。
我们不妨使用Segtree和Splaytree。
在线段树的每一个区间中添加相应的节点到Splay中,同时线段树记住相应的Splay根节点。
因为是裸的寻问,不存在修改操作,所以我们直接找出某一节点是否存在k-1个节点的值小于它,如果是就输出这个第K大的节点。
CODE
蒟蒻暴力乱开数组大小(反正不会MLE,开小后RE就悲剧了)
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
const int N=500005;
inline int read(){
char c;int rec=0;
while((c=getchar())<'0'||c>'9');
while(c>='0'&&c<='9')rec=rec*10+c-'0',c=getchar();
return rec;
}
int n,m;
int cnt,c[N];
struct Splay_Tree{
int F,s[2],size,val;
inline void NewNode(int fa,int x){
F=fa;val=x;s[0]=s[1]=0;size=1;return ;
}
}tree[4*N];
inline void Pushup(int v){tree[v].size=tree[tree[v].s[0]].size+1+tree[tree[v].s[1]].size;return ;}
inline void Rotate(int v){
int p=tree[v].F,g=tree[p].F;
int f1=(v==tree[p].s[1]),f2=(p==tree[g].s[1]),S=tree[v].s[!f1];
tree[g].s[f2]=v;tree[v].F=g;
tree[p].s[f1]=S;tree[S].F=p;
tree[v].s[!f1]=p;tree[p].F=v;
Pushup(p);return ;
}
inline void Splay(int v,int &root){
while(tree[v].F){
int p=tree[v].F,g=tree[p].F;
if(g)(v==tree[p].s[1])^(p==tree[g].s[1])?Rotate(v):Rotate(p);
Rotate(v);
}Pushup(v);root=v;
return ;
}
inline void Insert(int &root,int x){
int v=root,f;
if(!v){tree[++cnt].NewNode(0,x);root=cnt;return ;}
while(v){f=v;v=tree[v].s[x>tree[v].val];}
tree[++cnt].NewNode(f,x);
tree[f].s[x>tree[f].val]=cnt;
Splay(cnt,root);return ;
}
struct Seg_Tree{int L,R,root;}q[4*N];
inline void Build(int L,int R,int v){
q[v].L=L;q[v].R=R;q[v].root=0;
if(L==R){Insert(q[v].root,c[L]);return ;}
int mid=(L+R)>>1;
Build(L,mid,v<<1);Build(mid+1,R,v<<1|1);
for(int i=L;i<=R;i++)Insert(q[v].root,c[i]);
return ;
}
inline int Find(int L,int R,int v,int x){
if(q[v].L>R||q[v].R<L)return 0;
if(q[v].L>=L&&q[v].R<=R){
int p=q[v].root,rec=0;
while(p){
if(tree[p].val<x)rec+=tree[tree[p].s[0]].size+1,p=tree[p].s[1];
else p=tree[p].s[0];
}return rec;
}return Find(L,R,v<<1,x)+Find(L,R,v<<1|1,x);
}
inline void Ask(int L,int R,int x){
int v=q[1].root,ans,k=x-1;
while(v){
int p=Find(L,R,1,tree[v].val);
if(p<=k)ans=tree[v].val,v=tree[v].s[1];
else v=tree[v].s[0];
}cout<<ans<<'\n';
return ;
}
int main(){
n=read();m=read();
int i,x,y,z;
for(i=1;i<=n;i++)c[i]=read();
Build(1,n,1);
for(i=1;i<=m;i++){
x=read();y=read();z=read();
Ask(x,y,z);
}
return 0;
}