题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4006
题目思路:splay,动态求第k大数。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<string>
#include<queue>
#include<algorithm>
#include<vector>
#include<stack>
#include<list>
#include<iostream>
#include<map>
using namespace std;
#define inf 0x3f3f3f3f
#define Max 110
#define M 1001000
#define keytree ch[ch[root][1]][0]
int max(int a,int b)
{
return a>b?a:b;
}
int min(int a,int b)
{
return a<b?a:b;
}
int p[M],s[M],v[M],ch[M][2];
int top1,root;
void up(int x)
{
s[x]=s[ch[x][0]]+s[ch[x][1]]+1;
}
void newnode(int &x,int val,int pre)
{
x=++top1;
p[x]=pre;
s[x]=1;
v[x]=val;
ch[x][0]=ch[x][1]=0;
}
void init()
{
top1=0;
newnode(root,-inf,0);
newnode(ch[root][1],inf,root);
s[root]=2;
}
void rot(int x,int f)
{
int y=p[x];
p[ch[x][f]]=y;
ch[y][!f]=ch[x][f];
p[x]=p[y];
if(p[y]) ch[p[y]][ch[p[y]][1]==y]=x;
p[y]=x;
ch[x][f]=y;
up(y);
}
void splay(int x,int goal)
{
while(p[x]!=goal)
{
if(p[p[x]]==goal) rot(x,ch[p[x]][0]==x);
else
{
int y=p[x],f=ch[p[y]][0]==y;
if(ch[y][f]==x)
rot(x,!f);
else
rot(y,f);
rot(x,f);
}
}
if(!goal) root=x;
up(x);
}
void insert(int val)
{
int x=root;
while(ch[x][v[x]<val]) x=ch[x][v[x]<val];
newnode(ch[x][v[x]<val],val,x);
splay(ch[x][v[x]<val],0);
}
void findk(int k)
{
int x=root;
while(s[ch[x][1]]!=k)
{
if(s[ch[x][1]]>k)
x=ch[x][1];
else
{
k-=s[ch[x][1]]+1;
x=ch[x][0];
}
}
printf("%d\n",v[x]);
}
int main()
{
int n,k,a;
char op[10];
while(scanf("%d%d",&n,&k)!=EOF)
{
init();
while(n--)
{
scanf("%s",op);
if(op[0]=='I')
{
scanf("%d",&a);
insert(a);
// printf("s %d\n",s[root]);
}
else
findk(k);
}
}
return 0;
}