Cod sursa(job #3123824)

Utilizator PetyAlexandru Peticaru Pety Data 25 aprilie 2023 17:14:09
Problema Secv8 Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.64 kb
#include <bits/stdc++.h>

using namespace std;


ifstream fin ("secv8.in");
ofstream fout ("secv8.out");

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
int rand() {
  return std::uniform_int_distribution<int>(0, 1e9)(rng);
}


struct treap {
  int cnt, val, pr, rev;
  treap *l = NULL, *r = NULL;
  treap (int x): val(x), cnt(1), pr(rand()), rev(0) {};
  void push();
} *root;

int T(treap* n) {
  return (n?n->cnt:0);
} 

void treap::push() {
  cnt = 1 + T(l) + T(r);
  if (rev) {
    swap(l, r);
    if (l) l->rev ^= 1;
    if (r) r->rev ^= 1;
    rev = 0;
  }
}  

treap* merge (treap* st, treap* dr) {
  if (!st)
    return dr;
  if (!dr)
    return st;
  st->push();
  dr->push();
  if (st->pr > dr->pr) {
    st->r = merge(st->r, dr);
    st->push();
    return st;
  }
  else {
    dr->l = merge(st, dr->l);
    dr->push();
    return dr;
  }
}

pair<treap*, treap*> split (treap* nod, int poz) {
  if (!nod)
    return {nod, nod};
  nod->push();
  if (poz <= T(nod->l)) {
    auto r = split(nod->l, poz);
    nod->l = r.second;
    nod->push();
    return {r.first, nod};  
  }
  else {
    auto r = split(nod->r, poz - T(nod->l) - 1);
    nod->r = r.first;
    nod->push();
    return {nod, r.second};
  }
}

treap* add (treap* nod, int poz, int val) {
  pair<treap*, treap*> ans = split(nod, poz - 1);
  treap* newNode = new treap(val);
  return merge(merge(ans.first, newNode), ans.second);
}
treap* del (treap* nod, int st, int dr) {
  pair<treap*, treap*> p1 = split(nod, st - 1);
  pair<treap*, treap*> p2 = split(p1.second, dr - st + 1);
  return merge(p1.first, p2.second);
}
treap* inverse (treap* nod, int st, int dr) {
  pair<treap*, treap*> p1 = split(nod, st - 1);
  pair<treap*, treap*> p2 = split(p1.second, dr - st + 1);
  p2.first->rev ^= 1;
  return merge(merge(p1.first, p2.first), p2.second);
}
int el (treap* nod, int poz) {
  nod->push();
  if (T(nod->l) + 1 == poz)
    return nod->val;
  if (T(nod->l) >= poz)
    return el(nod->l, poz);
  else 
    return el(nod->r, poz - T(nod->l) - 1);
}

bool ok;
int Q, n;

int main () 
{
  ios_base::sync_with_stdio(false);
  cin.tie(0); cout.tie(0);
  
  fin >> Q >> ok;
  while (Q--) {
    char ch;
    fin >> ch;
    if (ch == 'I') {
      int a, b;
      fin >>a >> b;
      root = add(root, a, b);
      n++;
    }
    if (ch == 'A') {
      int a;
      fin >> a;
      fout << el(root, a) << "\n";
    }
    if (ch == 'R') {
      int a, b;
      fin >> a >> b;
      root = inverse(root, a, b);
    }
     if (ch == 'D') {
      int a, b;
      fin >> a >> b;
      root = del(root, a, b);
      n -= b - a + 1;
    }
    
  }
  for (int i = 1; i <= n; i++)
    fout << el(root, i) <<" ";
  return 0;
}