Cod sursa(job #2290931)

Utilizator MiricaMateiMirica Matei MiricaMatei Data 27 noiembrie 2018 10:36:05
Problema Secv8 Scor 25
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.7 kb
#include <bits/stdc++.h>

using namespace std;

struct Node {
  Node* l;
  Node* r;
  int val, sz, prio;
  bool rev;
};

Node* e = new Node {NULL, NULL, 0, 0, 0, 0};

void rec(Node* root) {
  root->sz = root->l->sz + 1 + root->r->sz;
}

void unrev(Node* root) {
  if (root != e && root->rev) {
    root->rev = 0;
    root->l->rev ^= 1;
    root->r->rev ^= 1;
    swap(root->l, root->r);
  }
}

pair<Node*, Node*> split(Node* root, int pos) {
  unrev(root);
  if (root == e)
    return {e, e};
  pair<Node*, Node*>ans;
  if (root->l->sz >= pos) {
    ans.second = root;
    pair<Node*, Node*>aux = split(root->l, pos);
    ans.first = aux.first;
    ans.second->l = aux.second;
    rec(ans.second);
  } else {
    ans.first = root;
    pair<Node*, Node*> aux = split(root->r, pos - root->l->sz - 1);
    ans.second = aux.second;
    ans.first->r = aux.first;
    rec(ans.first);
  }
  return ans;
}

Node* join(Node* a, Node* b) {
  unrev(a);
  unrev(b);
  if (a == e)
    return b;
  if (b == e)
    return a;
  if (a->prio > b->prio) {
    a->r = join(a->r, b);
    rec(a);
    return a;
  } else {
    b->l = join(a, b->l);
    rec(b);
    return b;
  }
}

Node* ins(Node* root, int pos, int val) {
  Node* nt = new Node {e, e, val, 1, rand(), 0};
  pair<Node*, Node*>aux = split(root, pos - 1);
  return join(join(aux.first, nt), aux.second);
}

Node* del(Node* root, int l, int r) {
  pair<Node*, Node*>aux1 = split(root, l - 1);
  pair<Node*, Node*>aux2 = split(aux1.second, r - l + 1);
  return join(aux1.first, aux2.second);
}

Node* rev(Node* root, int l, int r) {
  pair<Node*, Node*>aux1 = split(root, l - 1);
  pair<Node*, Node*>aux2 = split(aux1.second, r - l + 1);
  aux2.first->rev ^= 1;
  return join(join(aux1.first, aux2.first), aux2.second);
}

int ac(Node* root, int pos) {
  if (root->l->sz + 1 == pos)
    return root->val;
  if (root->l->sz >= pos)
    return ac(root->l, pos);
  return ac(root->r, pos - root->l->sz - 1);
}

int main() {
  freopen("secv8.in", "r", stdin);
  freopen("secv8.out", "w", stdout);

  int n, k;
  scanf("%d%d ", &n, &k);
  Node* root = e;
  for (int i = 1; i <= n; ++i) {
    char c;
    scanf("%c", &c);
    if (c == 'I') {
      int k, e;
      scanf("%d%d ", &k, &e);
      root = ins(root, k, e);
    } else if (c == 'A') {
      int k;
      scanf("%d ", &k);
      printf("%d\n", ac(root, k));
    } else if (c == 'R') {
      int l, r;
      scanf("%d%d ", &l, &r);
      root = rev(root, l, r);
    } else {
      int l, r;
      scanf("%d%d ", &l, &r);
      root = del(root, l, r);
    }
  }

  for (int i = 1; i <= root->sz; ++i)
    printf("%d ", ac(root, i));

  return 0;
}