RankTree.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // Rank Tree
  2. // m m operations.
  3. // 1 x insert x
  4. // 2 x delete x; return 1(succes) 0(failed)
  5. // 3 k output the k-th smallest element. k=1 for the smallest.
  6. // 4 x output the rank of x
  7. struct Node {
  8. Node *ch[2]; //left and right subtree.
  9. int r; // randomized order. structure -> heap
  10. int v; // key structure -> BST
  11. int s; // the number of nodes
  12. Node(int v = 0):v(v) { ch[0] = ch[1] = NULL; r = rand(); s = 1; }
  13. int cmp(int x) const {
  14. if (x == v) return -1;
  15. return x < v ? 0 : 1;
  16. }
  17. void maintain() {
  18. s = 1;
  19. if(ch[0] != NULL) s += ch[0]->s;
  20. if(ch[1] != NULL) s += ch[1]->s;
  21. }
  22. };
  23. void rotate(Node* &o, int d) {
  24. Node* k = o->ch[d^1]; o->ch[d^1] = k->ch[d]; k->ch[d] = o;
  25. o->maintain(); k->maintain(); o = k;
  26. }
  27. void insert(Node* &o, int x) {
  28. if(o == NULL) o = new Node(x);
  29. else {
  30. int d = (x < o->v ? 0 : 1);
  31. insert(o->ch[d], x);
  32. if(o->ch[d]->r > o->r) rotate(o, d^1);
  33. }
  34. o->maintain();
  35. }
  36. Node* find(Node* o, int x) {
  37. if(o == NULL) return NULL;
  38. if(x == o->v) return o;
  39. return x < o->v ? find(o->ch[0], x) : find(o->ch[1], x);
  40. }
  41. void remove(Node* &o, int x) {
  42. int d = o->cmp(x);
  43. //int ret = 0;
  44. if(d == -1) {
  45. Node* u = o;
  46. if(o->ch[0] != NULL && o->ch[1] != NULL) {
  47. int d2 = (o->ch[0]->r > o->ch[1]->r ? 1 : 0);
  48. rotate(o, d2); remove(o->ch[d2], x);
  49. } else {
  50. if(o->ch[0] == NULL) o = o->ch[1]; else o = o->ch[0];
  51. delete u;
  52. }
  53. } else
  54. remove(o->ch[d], x);
  55. if(o != NULL) o->maintain();
  56. }
  57. int kth(Node* o, int k) {
  58. if(o == NULL || k <= 0 || k > o->s) return 0;
  59. int s = (o->ch[0] == NULL ? 0 : o->ch[0]->s);
  60. if(k == s+1) return o->v;
  61. else if(k <= s) return kth(o->ch[0], k);
  62. else return kth(o->ch[1], k-s-1);
  63. }
  64. // in the tree rooted at o.
  65. int rank(Node* o, int x) {
  66. if(o == NULL) return 1;
  67. if(x <= o->v) return rank(o->ch[0], x);
  68. return rank(o->ch[1], x) + (o->ch[0] == NULL ? 0 : o->ch[0]->s) + 1;
  69. }
  70. int main() {
  71. int m, c, v;
  72. Node* root = new Node(INF);
  73. while(scanf("%d", &m) == 1) {
  74. while(m--) {
  75. scanf("%d%d", &c, &v);
  76. if(c == 1) insert(root, v);
  77. else if(c == 2) {
  78. Node* o = find(root, v);
  79. printf("%d\n", o == NULL ? 0 : 1);
  80. if(o != NULL) remove(root, v);
  81. }
  82. else if(c == 3) printf("%d\n", kth(root, v));
  83. else if(c == 4) printf("%d\n", rank(root, v));
  84. }
  85. }
  86. return 0;
  87. }