The kth great number
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65768/65768 K (Java/Others)
Total Submission(s): 6228 Accepted Submission(s): 2526
Problem Description
Xiao Ming and Xiao Bao are playing a simple Numbers game. In a round Xiao Ming can choose to write down a number, or ask Xiao Bao what the kth great number is. Because the number written by Xiao Ming is too much, Xiao Bao is feeling giddy. Now, try to help Xiao Bao.
Input
There are several test cases. For each test case, the first line of input contains two positive integer n, k. Then n lines follow. If Xiao Ming choose to write down a number, there will be an " I" followed by a number that Xiao Ming will write down. If Xiao Ming choose to ask Xiao Bao, there will be a "Q", then you need to output the kth great number.
Output
The output consists of one integer representing the largest number of islands that all lie on one line.
Sample Input
8 3 I 1 I 2 I 3 Q I 5 Q I 4 Q
Sample Output
1 2 3HintXiao Ming won't ask Xiao Bao the kth great number when the number of the written number is smaller than k. (1=<k<=n<=1000000).
Source
Recommend
题意:n次操作,I的时候插入x,Q的时候查询第k大元素。
思路: 统计当前到目前操作为止共插入的元素个数cnt,查询第k大,相当于查询第cnt-k+1小。详见代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int MAXN=1000000+100;
int n,k;
struct node
{
node *next[2];
int r,v,s;
node(int x){
v=x; s=1; r=rand();
next[0]=next[1]=NULL;
}
bool operator <(const node &rhs) const { // 根据优先级比较结点
return r<rhs.r;
}
int cmp(int x){
if(v == x) return -1;
return x<v ? 0 : 1;
}
void maintain(){
s=1;
if(next[0]!=NULL) s+=next[0]->s;
if(next[1]!=NULL) s+=next[1]->s;
}
};
struct Treap
{
inline void rotate(node * &rt,int d){ // d=0,左旋,d=1,右旋
node *k=rt->next[d^1]; rt->next[d^1]=k->next[d];
k->next[d]=rt; rt->maintain(); k->maintain(); rt=k;
}
inline void insert(node * &rt,int x){
if(rt == NULL) rt=new node (x);
else {
int d= x< rt->v ? 0 : 1;
insert(rt->next[d],x);
if(rt->next[d]->r >rt->r)
rotate(rt,d^1); // 维护堆的性质
}
rt->maintain();
}
inline void remove(node * &rt,int x){
int d=rt->cmp(x);
if(d == -1){
node *u=rt;
if(rt->next[0]!=NULL && rt->next[1]!=NULL){
int d1=rt->next[0]->r > rt->next[1]->r ? 1 : 0;
rotate(rt,d1); remove(rt->next[d1],x);
}
else {
if(rt->next[0]==NULL)
rt=rt->next[1];
else
rt=rt->next[0];
delete u;
}
}
else
remove(rt->next[d],x);
if(rt!=NULL)
rt->maintain();
}
inline int kth(node *rt,int k){
if( rt == NULL || k<=0 || k> rt->s ) return 0;
int num= rt->next[0] == NULL ? 0 : rt->next[0]->s;
if(k == num+1 ) return rt->v;
else if( k<= num ) return kth(rt->next[0],k);
else return kth(rt->next[1],k-num-1);
}
}treap;
int main()
{
//freopen("text.txt","r",stdin);
while(~scanf("%d%d",&n,&k))
{
node *rt=NULL;
int x; char str[2];
int cnt=0;
for(int i=1;i<=n;i++)
{
scanf("%s",str);
if(str[0]=='I')
{
scanf("%d",&x);
++cnt;
treap.insert(rt,x);
}
else
printf("%d\n",treap.kth(rt,cnt-k+1));
}
}
return 0;
}