Topic Links: http://acm.hdu.edu.cn/showproblem.php?pid=5249
Thinking Analysis: use the queue to record the values in the pipeline and use Treap to query the function of the K-large to query the value of floor (M/2) +1;
For the in value operation, the value is inserted into the queue and treap, and for the out operation, the queue Squadron head element is deleted in Treap and the team head element is removed from the queue;
For the query operation, because the value of Tail–head is the number of values in the pipeline, use Treap to query the first floor ((Tail–head)/2) + 1 large elements;
The code is as follows:
#include <cstdio>#include<ctime>#include<cstring>#include<iostream>using namespacestd;Const intMax_n =10000+ -;intQueue[max_n];structnode{Node*ch[2]; intvalue, key; intsize; intcmpintXConst{ if(x = = value)return-1; returnX < value?0:1; } voidmaintain () {size=1; if(ch[0]! = NULL) Size + = ch[0]->size; if(ch[1]! = NULL) Size + = ch[1]->size; }};voidRotate (Node *&o,intd) {Node*k = o->ch[d ^1]; o->ch[d ^1] = k->Ch[d]; K->CH[D] =o; o-maintain (); K-maintain (); o=K;}voidInsert (Node *&o,intx) { if(O = =NULL) {o=NewNode (); o->ch[0] = o->ch[1] =NULL; o->value =x; o->key =rand (); } Else{ intD = (x < (o->value)?0:1); Insert (o-Ch[d], x); if(O->ch[d]->key > o->key) Rotate (o, D^1); } o-maintain ();}voidRemove (Node *&o,intx) { intD = o->CMP (x); if(d = =-1) {Node*u =o; if(o->ch[0]! = NULL && o->ch[1] !=NULL) { intD2 = (o->ch[0]->key > o->ch[1]->key?1:0); Rotate (o, D2); Remove (o-CH[D2], x); }Else{ if(o->ch[0] ==NULL) o= o->ch[1]; Elseo= o->ch[0]; Deleteu; } }ElseRemove (o-Ch[d], x); if(O! =NULL) o-maintain ();}intFind (Node *o,intx) { while(O! =NULL) { intD = o->CMP (x); if(d = =-1)return 1; Elseo = o->Ch[d]; } return 0;}intFindkth (Node *o,intk) { intL_size = (o->ch[0] = = NULL?0: o->ch[0]->size); if(k = = L_size +1) returnO->value; Else if(k <=l_size)returnFindkth (o->ch[0], k); Else returnFindkth (o->ch[1], K-l_size-1);}voidMakeempty (Node *root) { if(Root = =NULL)return; if(root->ch[0]) makeempty (Root->ch[0]); if(root->ch[1]) makeempty (Root->ch[1]); DeleteRoot;}intMain () {intN, case_id =0, value; Srand ( -); while(SCANF ("%d", &n)! =EOF) {Node*root =NULL; intHead =0, tail =0, ans; Charstr[Ten]; printf ("Case #%d:\n", ++case_id); for(inti =0; I < n; ++i) {scanf ("%s", str); if(str[0] =='I') {scanf ("%d", &value); Queue[tail++] =value; Insert (root, value); } Else if(str[0] =='o') Remove (root, Queue[head++]); Else{ans= Findkth (root, (tail-head)/2+1); printf ("%d\n", ans); }} makeempty (root); } return 0;}
Hdoj 5249 KPI (treap)