POJ--3481(Treap / other trees / STL)
2015-03-20 00:44:34
思路:无聊拿来写treap练练手... 插入、删除都是常规的,至于找最大和找最小,每个节点的key值令为客户的priority,再保存他的编号即可。
(因为查询时没写全局,而用了pair作为返回TLE了... 看来pair返回还是很慢的... 尽量开在全局吧...)
1 #include <cstdio> 2 #include <cstring> 3 #include <cstdlib> 4 #include <cmath> 5 #include <vector> 6 #include <map> 7 #include <set> 8 #include <stack> 9 #include <queue> 10 #include <string> 11 #include <iostream> 12 #include <algorithm> 13 using namespace std; 14 15 #define MEM(a,b) memset(a,b,sizeof(a)) 16 #define REP(i,n) for(int i=1;i<=(n);++i) 17 #define REV(i,n) for(int i=(n);i>=1;--i) 18 #define FOR(i,a,b) for(int i=(a);i<=(b);++i) 19 #define RFOR(i,a,b) for(int i=(a);i>=(b);--i) 20 #define getmid(l,r) ((l) + ((r) - (l)) / 2) 21 #define MP(a,b) make_pair(a,b) 22 #define X first 23 #define Y second 24 25 typedef long long ll; 26 typedef pair<int,int> pii; 27 const int INF = (1 << 30) - 1; 28 const int MAXN = 1e6; 29 30 int ID,KEY; 31 32 struct Treap{ 33 int root,tcnt; 34 int key[MAXN],pro[MAXN],id[MAXN],son[MAXN][2]; 35 inline void clear(){ 36 root = 0; 37 tcnt = 0; 38 pro[0] = ~0U >> 1; 39 id[0] = key[0] = 0; 40 } 41 inline void rotate(int &x,int t){ 42 int y = son[x][t]; 43 son[x][t] = son[y][1 - t]; 44 son[y][1 - t] = x; 45 x = y; 46 } 47 inline void _insert(int &x,int k,int tid){ 48 if(x){ //not empty 49 if(key[x] != k){ 50 int t = k > key[x]; 51 _insert(son[x][t],k,tid); 52 if(pro[son[x][t]] < pro[x]) rotate(x,t); 53 } 54 } 55 else{ 56 x = ++tcnt; 57 key[x] = k; 58 id[x] = tid; 59 pro[x] = rand(); 60 son[x][0] = son[x][1] = 0; 61 } 62 } 63 inline void _erase(int &x,int k){ 64 if(key[x] == k){ 65 if(!son[x][0] && !son[x][1]){ 66 x = 0; 67 return; 68 } 69 int t = pro[son[x][0]] > pro[son[x][1]]; 70 rotate(x,t); 71 _erase(x,k); 72 } 73 else _erase(son[x][k > key[x]],k); 74 } 75 inline void _top(int &x){ 76 if(!son[x][1]){ 77 ID = id[x]; 78 KEY = key[x]; 79 return; 80 } 81 else _top(son[x][1]); 82 } 83 inline void _bot(int &x){ 84 if(!son[x][0]){ 85 ID = id[x]; 86 KEY = key[x]; 87 return; 88 } 89 else _bot(son[x][0]); 90 } 91 inline void insert(int k,int tid){ 92 _insert(root,k,tid); 93 } 94 inline void erase(int k){ 95 _erase(root,k); 96 } 97 inline void top(){ 98 return _top(root); 99 } 100 inline void bot(){ 101 return _bot(root); 102 } 103 }tp; 104 105 int main(){ 106 int a,b,c; 107 tp.clear(); 108 while(scanf("%d",&a) != EOF){ 109 if(a == 0) break; 110 if(a == 2){ 111 tp.top(); 112 printf("%d\n",ID); 113 if(KEY) tp.erase(KEY); 114 } 115 else if(a == 3){ 116 tp.bot(); 117 printf("%d\n",ID); 118 if(KEY) tp.erase(KEY); 119 } 120 else{ 121 scanf("%d%d",&b,&c); 122 tp.insert(c,b); 123 } 124 } 125 return 0; 126 }