标签:
又一道数据结构的题目,用Treap可以轻松解决。
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, info; 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 = 1; 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, int info ) 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->info = info; 44 o->size = 1; 45 } 46 else 47 { 48 int d = o->cmp(x); 49 insert( o->ch[d], x, info ); 50 if ( o->ch[d]->r > o->r ) 51 { 52 rotate( o, d ^ 1 ); 53 } 54 else 55 { 56 o->maintain(); 57 } 58 } 59 } 60 61 void remove( Node * & o, int x ) 62 { 63 int d = o->cmp(x); 64 if ( d == -1 ) 65 { 66 if ( o->ch[0] != NULL && o->ch[1] != NULL ) 67 { 68 int dd = ( o->ch[0]->r > o->ch[1]->r ? 1 : 0 ); 69 rotate( o, dd ); 70 remove( o->ch[dd], x ); 71 } 72 else 73 { 74 Node * u = o; 75 if ( o->ch[0] == NULL ) o = o->ch[1]; 76 else o = o->ch[0]; 77 delete u; 78 } 79 } 80 else 81 { 82 remove( o->ch[d], x ); 83 } 84 if ( o != NULL ) o->maintain(); 85 } 86 87 int ans_info, ans_v; 88 89 void findmin( Node * o ) 90 { 91 while ( o->ch[0] != NULL ) 92 { 93 o = o->ch[0]; 94 } 95 ans_v = o->v; 96 ans_info = o->info; 97 } 98 99 void findmax( Node * o ) 100 { 101 while ( o->ch[1] != NULL ) 102 { 103 o = o->ch[1]; 104 } 105 ans_v = o->v; 106 ans_info = o->info; 107 } 108 109 int main () 110 { 111 int op; 112 Node * root = NULL; 113 while ( scanf("%d", &op), op ) 114 { 115 if ( op == 1 ) 116 { 117 int info, x; 118 scanf("%d%d", &info, &x); 119 insert( root, x, info ); 120 } 121 else if ( op == 2 ) 122 { 123 if ( root == NULL ) 124 { 125 printf("0\n"); 126 } 127 else 128 { 129 findmax(root); 130 printf("%d\n", ans_info); 131 remove( root, ans_v ); 132 } 133 } 134 else 135 { 136 if ( root == NULL ) 137 { 138 printf("0\n"); 139 } 140 else 141 { 142 findmin(root); 143 printf("%d\n", ans_info); 144 remove( root, ans_v ); 145 } 146 } 147 } 148 return 0; 149 }
标签:
原文地址:http://www.cnblogs.com/huoxiayu/p/4695870.html