标签:
模板题,以后要学splay,大概看一下treap就好了。
1 #include <cstdio> 2 #include <algorithm> 3 #include <cstring> 4 5 using namespace std; 6 7 const int maxn = 3e5+10; 8 int num[maxn],st[maxn]; 9 10 struct Treap{ 11 int size; 12 int key,fix; 13 Treap *ch[2]; 14 15 Treap(int key) 16 { 17 size = 1; 18 fix = rand(); 19 this->key = key; 20 ch[0] = ch[1] = NULL; 21 } 22 int compare(int x) const 23 { 24 if(x == key) return -1; 25 return x < key ? 0 : 1; 26 } 27 void Maintain() 28 { 29 size = 1; 30 if(ch[0] != NULL) size += ch[0]->size; 31 if(ch[1] != NULL) size += ch[1]->size; 32 } 33 }; 34 35 void Rotate(Treap* &t ,int d) 36 { 37 Treap *k = t->ch[d^1]; 38 t->ch[d^1] = k->ch[d]; 39 k->ch[d] = t; 40 t->Maintain(); 41 k->Maintain(); 42 t = k; 43 } 44 45 void Insert(Treap* &t,int x) 46 { 47 if(t == NULL) t = new Treap(x); 48 else 49 { 50 int d = x < t->key ? 0 : 1; 51 Insert(t->ch[d],x); 52 if(t->ch[d]->fix > t->fix) 53 Rotate(t,d^1); 54 } 55 t->Maintain(); 56 } 57 58 void Delete(Treap* &t,int x) 59 { 60 int d = t->compare(x); 61 if(d == -1) 62 { 63 Treap *tmp = t; 64 if(t->ch[0] == NULL) 65 { 66 t = t->ch[1]; 67 delete tmp; 68 tmp = NULL; 69 } 70 else if(t->ch[1] == NULL) 71 { 72 t = t->ch[0]; 73 delete tmp; 74 tmp = NULL; 75 } 76 else 77 { 78 int k = t->ch[0]->fix > t->ch[1]->fix ? 1 : 0; 79 Rotate(t,k); 80 Delete(t->ch[k],x); 81 } 82 } 83 else Delete(t->ch[d],x); 84 if(t!=NULL) t->Maintain(); 85 } 86 87 bool Find(Treap *t,int x) 88 { 89 while(t != NULL) 90 { 91 int d = t->compare(x); 92 if(d == -1) return true; 93 t = t->ch[d]; 94 } 95 return false; 96 } 97 98 int Kth(Treap *t,int k) 99 { 100 if(t == NULL || k <= 0 || k > t->size) 101 return -1; 102 if(t->ch[0] == NULL && k == 1) 103 return t->key; 104 if(t->ch[0] == NULL) 105 return Kth(t->ch[1],k-1); 106 if(t->ch[0]->size >= k) 107 return Kth(t->ch[0],k); 108 if(t->ch[0]->size + 1 == k) 109 return t->key; 110 return Kth(t->ch[1],k-1-t->ch[0]->size); 111 } 112 113 int Rank(Treap *t,int x) 114 { 115 int r; 116 if(t->ch[0] == NULL) r = 0; 117 else r = t->ch[0]->size; 118 if(x == t->key) return r+1; 119 if(x < t->key) 120 return Rank(t->ch[0],x); 121 return r+1+Rank(t->ch[1],x); 122 } 123 124 void DeleteTreap(Treap* &t) 125 { 126 if(t == NULL) return; 127 if(t->ch[0] != NULL) DeleteTreap(t->ch[0]); 128 if(t->ch[1] != NULL) DeleteTreap(t->ch[1]); 129 delete t; 130 t = NULL; 131 } 132 133 int save[maxn]; 134 int M,N; 135 136 int main() 137 { 138 while(~scanf("%d%d",&M,&N)) 139 { 140 for(int i=1;i<=M;i++) 141 scanf("%d",&save[i]); 142 Treap *root = NULL; 143 int cnt = 1; 144 for(int i=1,x;i<=N;i++) 145 { 146 scanf("%d",&x); 147 for(int j = cnt;j <= x;j++) 148 Insert(root,save[j]); 149 cnt = x+1; 150 printf("%d\n",Kth(root,i)); 151 } 152 DeleteTreap(root); 153 } 154 }
标签:
原文地址:http://www.cnblogs.com/helica/p/5492570.html