Cod sursa(job #3123803)

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

using namespace std;


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

struct treap {
  int cnt, val, pr, rev;
  treap *l = NULL, *r = NULL;
  treap (int x): val(x), cnt(1), pr(rand()), rev(0) {};
  int T () {
    return (this == NULL ? 0 : cnt);
  }
  void push() {
    if (this == NULL)
      return;
    cnt = 1 + l->T() + r->T();
    if (rev) {
      swap(l, r);
      if (l) l->rev ^= 1;
      if (r) r->rev ^= 1;
      rev = 0;
    }
  }  
} *root;

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 <= nod->l->T()) {
    auto r = split(nod->l, poz);
    nod->l = r.second;
    nod->push();
    return {r.first, nod};  
  }
  else {
    auto r = split(nod->r, poz - nod->l->T() - 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 (nod->l->T() + 1 == poz)
    return nod->val;
  if (nod->l->T() >= poz)
    return el(nod->l, poz);
  else 
    return el(nod->r, poz - nod->l->T() - 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;
}