码迷,mamicode.com
首页 > 其他好文 > 详细

hdu 4006 Treap

时间:2015-08-02 16:47:20      阅读:91      评论:0      收藏:0      [点我收藏+]

标签:

继续测模板...

  1 #include <iostream>
  2 #include <cstring>
  3 #include <cstdlib>
  4 #include <cstdio>
  5 #include <ctime>
  6 using namespace std;
  7 
  8 struct Node 
  9 {
 10     Node * ch[2];
 11     int v, r, size, cnt;
 12     int cmp( int x )
 13     {
 14         if ( x == v ) return -1;
 15         return x < v ? 0 : 1;
 16     }    
 17     void maintain()
 18     {
 19         size = cnt;
 20         if ( ch[0] != NULL ) size += ch[0]->size;
 21         if ( ch[1] != NULL ) size += ch[1]->size;
 22     }
 23 };
 24 
 25 void rotate( Node * & o, int d )
 26 {
 27     Node * k = o->ch[d ^ 1];
 28     o->ch[d ^ 1] = k->ch[d];
 29     k->ch[d] = o;
 30     o->maintain();
 31     k->maintain();
 32     o = k;
 33 }
 34 
 35 void insert( Node * & o, int x )
 36 {
 37     if ( o == NULL )
 38     {
 39         o = new Node();
 40         o->ch[0] = o->ch[1] = NULL;
 41         o->v = x;
 42         o->r = rand();
 43         o->size = o->cnt = 1;
 44     }
 45     else
 46     {
 47         int d = o->cmp(x);
 48         if ( d == -1 )
 49         {
 50             o->cnt++;
 51             o->size++;
 52         }
 53         else
 54         {
 55             insert( o->ch[d], x );
 56             if ( o->ch[d]->r > o->r )
 57             {
 58                 rotate( o, d ^ 1 );
 59             }
 60             else
 61             {
 62                 o->maintain();
 63             }
 64         }
 65     }
 66 }
 67 
 68 int kth( Node * o, int k )
 69 {
 70     int tmp = ( o->ch[0] == NULL ? 0 : o->ch[0]->size );
 71     if ( k >= tmp + 1 && k <= tmp + o->cnt ) return o->v;
 72     else if ( k < tmp + 1 ) return kth( o->ch[0], k );
 73     else return kth( o->ch[1], k - tmp - o->cnt );
 74 }
 75 
 76 void clear( Node * o )
 77 {
 78     if ( o == NULL ) return ;
 79     clear( o->ch[0] );
 80     clear( o->ch[1] );
 81     delete o;
 82 }
 83 
 84 int main ()
 85 {
 86     int n, k;
 87     while ( scanf("%d%d", &n, &k) != EOF )    
 88     {
 89         Node * root = NULL;
 90         char op[2];
 91         for ( int i = 0; i < n; i++ )
 92         {
 93             scanf("%s", op);
 94             if ( op[0] == I )
 95             {
 96                 int tmp;
 97                 scanf("%d", &tmp);
 98                 insert( root, tmp );
 99             }
100             else
101             {
102                 printf("%d\n", kth( root, root->size + 1 - k ));
103             }
104         }
105         clear(root);
106         root = NULL;
107     }
108     return 0;
109 }

 

hdu 4006 Treap

标签:

原文地址:http://www.cnblogs.com/huoxiayu/p/4695924.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!