Advertisement
Guest User

Untitled

a guest
Jun 26th, 2014
1,117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.79 KB | None | 0 0
  1. #include <iostream>
  2. #include <cassert>
  3. #include <algorithm>
  4. using namespace std;
  5.  
  6. inline int gcd(int a, int b){
  7.     return b ? gcd(b,a%b) : a;
  8. }
  9.  
  10. struct item {
  11.     int key, prior, gcd;
  12.     item * l, * r;
  13.     item() { }
  14.     item (int key, int prior) : key(key), prior(prior), l(NULL), r(NULL), gcd(key) { }
  15. };
  16. typedef item * pitem;
  17.  
  18. int gcd (pitem it) {
  19.     return it ? it->gcd : 0;
  20. }
  21.  
  22. void upd_gcd (pitem it) {
  23.     if (it)
  24.         it->gcd = gcd(gcd(gcd(it->l),gcd(it->r)),it->key);
  25. }
  26.  
  27. void split (pitem t, int key, pitem & l, pitem & r) {
  28.     if (!t)
  29.         l = r = NULL;
  30.     else if (key < t->key)
  31.         split (t->l, key, l, t->l),  r = t;
  32.     else
  33.         split (t->r, key, t->r, r),  l = t;
  34.     upd_gcd(t);
  35. }
  36.  
  37. void insert (pitem & t, pitem it) {
  38.     if (!t)
  39.         t = it;
  40.     else if (it->prior > t->prior)
  41.         split (t, it->key, it->l, it->r),  t = it;
  42.     else
  43.         insert (it->key < t->key ? t->l : t->r, it);
  44.     upd_gcd(t);
  45. }
  46.  
  47. void merge (pitem & t, pitem l, pitem r) {
  48.     if (!l || !r)
  49.         t = l ? l : r;
  50.     else if (l->prior > r->prior)
  51.         merge (l->r, l->r, r),  t = l;
  52.     else
  53.         merge (r->l, l, r->l),  t = r;
  54.     upd_gcd(t);
  55. }
  56.  
  57. void erase (pitem & t, int key) {
  58.     if (t->key == key)
  59.         merge (t, t->l, t->r);
  60.     else
  61.         erase (key < t->key ? t->l : t->r, key);
  62.     upd_gcd(t);
  63. }
  64.  
  65. int priorities[100005];
  66.  
  67. int main(){
  68. #ifdef KP_HOME
  69.     freopen("input.txt","r",stdin);
  70.     freopen("output.txt","w",stdout);
  71. #endif
  72.     int t;
  73.     scanf("%d\n",&t);
  74.     pitem root = NULL;
  75.     for (int i=0; i<t; ++i) priorities[i] = i;
  76.     random_shuffle(priorities, priorities+t);
  77.  
  78.     while (t--){
  79.         char cmd;
  80.         int x;
  81.         scanf("%c %d\n",&cmd,&x);
  82.         pitem it;
  83.         if (cmd == '+'){
  84.             it = new item(x,priorities[t]);
  85.             insert(root, it);
  86.         } else if (cmd == '-'){
  87.             erase(root, x);
  88.         } else assert(false);
  89.  
  90.         printf("%d\n", root == NULL ? 1 : root->gcd);
  91.     }
  92.     return 0;
  93. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement