Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <algorithm>
- #include <random>
- #include <time.h>
- using namespace std;
- int gcd(int a,int b){
- while(b!=0){
- a%=b;
- swap(a,b);
- }
- return a;
- }
- int superRand(){
- return (rand() << 15)+rand();
- }
- struct Node{
- int key,prior;
- int g,sz;
- Node * left, * right;
- Node(): left(nullptr),right(nullptr),g(1),sz(0) {};
- Node(int key1): key(key1),prior(superRand()),left(nullptr),right(nullptr),g(key1),sz(1) {};
- };
- Node * root = nullptr;
- int get_g(Node * &root){
- if(!root){
- return 0;
- }
- return root->g;
- }
- int get_sz(Node * &root) {
- if (!root) {
- return 0;
- }
- return root->sz;
- }
- void update(Node * &root){
- if(!root)
- return;
- root->g = gcd(root->key,gcd(get_g(root->left),get_g(root->right)));
- root->sz = get_sz(root->left) + get_sz(root->right) + 1;
- }
- void split(Node * root, Node*&left, Node *&right, int x){
- if(!root){
- left = nullptr;
- right = nullptr;
- return;
- }
- if(root->key < x){
- split(root->right,root->right,right,x);
- left = root;
- update(left);
- update(root);
- return;
- }
- split(root->left,left,root->left,x);
- right = root;
- update(right);
- update(root);
- }
- void mmerge(Node * &root,Node * left, Node * right){
- if(!left){
- root = right;
- return;
- }
- if(!right){
- root = left;
- return;
- }
- if(left->prior > right->prior){
- mmerge(left->right,left->right,right);
- root = left;
- }
- else{
- mmerge(right->left,left,right->left);
- root = right;
- }
- update(root);
- }
- void minsert(Node * &root,Node * x){
- if(!root){
- root = x;
- return;
- }
- if(x->prior > root->prior){
- split(root,x->left,x->right,x->key);
- root = x;
- }
- else
- minsert(root->key > x->key ? root->left : root->right,x);
- update(root);
- }
- void merase(Node * &root, int x){
- if(!root){
- return;
- }
- if(root->key==x){
- mmerge(root,root->left,root->right);
- }
- else
- merase(root->key > x ? root->left : root->right,x);
- update(root);
- }
- bool mfind(Node * root,int x){
- if(!root)
- return false;
- if(root->key==x)
- return true;
- mfind(root->key > x ? root->left : root->right,x);
- }
- void Print(Node * root){
- if(!root)
- return;
- Print(root->left);
- cout << root->key << " ";
- Print(root->right);
- }
- void print(Node * root){
- Print(root);
- cout << endl;
- }
- int main()
- {
- ios_base::sync_with_stdio(0);
- cin.tie(0);
- int q;
- cin >> q;
- for(int i = 0;i<q;++i){
- char type;
- int x;
- cin >> type >> x;
- if(type=='+'){
- minsert(root,new Node(x));
- cout << get_g(root) << endl;
- }
- else{
- merase(root,x);
- if(get_sz(root)==0)
- cout << 1 << endl;
- else
- cout << get_g(root) << endl;
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement