Cod sursa(job #2757350)

Utilizator siliviuSilion Liviu siliviu Data 5 iunie 2021 01:14:26
Problema Secv8 Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.85 kb
#include <bits/stdc++.h>

using namespace std;
using T = int;

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

struct node {
    T v;
    int w, s, rev = 0;
    long long sum = 0;
    node* l = 0, * r = 0;
    node(T _v) : s(1), v(_v), sum(_v), w(rand()) {};
} *root;

void update(node* nod) {
    if (nod) {
        nod->s = (nod->l ? nod->l->s : 0) + (nod->r ? nod->r->s : 0) + 1;
        nod->sum = (nod->l ? nod->l->sum : 0) + (nod->r ? nod->r->sum : 0) + nod->v;
    }
}

void propagate(node* nod) {
    if (!nod || !nod->rev) return;
    swap(nod->l, nod->r);
    if (nod->l)
        nod->l->rev ^= 1;
    if (nod->r)
        nod->r->rev ^= 1;
    nod->rev = 0;
}

pair<node*, node*> split(node* n, int pos) {
    if (!n)
        return {0,0};
    propagate(n);
    pair<node*, node*> ans;
    if (pos <= (n->l ? n->l->s : 0)) {
        ans.second = n;
        node* ll, * rr;
        tie(ll, rr) = split(n->l, pos);
        ans.first = ll;
        ans.second->l = rr;
        update(ans.second);
    }
    else {
        ans.first = n;
        node* ll, * rr;
        tie(ll, rr) = split(n->r, pos - (n->l ? n->l->s : 0) - 1);
        ans.second = rr;
        ans.first->r = ll;
        update(ans.first);
    }
    return ans;
}

node* join(node* nl, node* nr) {
    if (!nl)
        return nr;
    if (!nr)
        return nl;
    propagate(nl), propagate(nr);
    if (nl->w > nr->w) {
        nl->r = join(nl->r, nr);
        update(nl);
        return nl;
    }
    nr->l = join(nl, nr->l);
    update(nr);
    return nr;
}

void insert(node*& n, int pos, T val) {
    node* l, * r;
    tie(l, r) = split(n, pos - 1);
    n = join(join(l, new node(val)), r);
}

T kth(node* n, int pos) {
    propagate(n);
    if (pos == ((n->l ? n->l->s : 0) + 1))
        return n->v;
    if (pos <= (n->l ? n->l->s : 0))
        return kth(n->l, pos);
    return kth(n->r, pos - (n->l ? n->l->s : 0) - 1);
}

void dfs(node* n) {
    if (!n) return;
    propagate(n);
    dfs(n->l);
    fout << n->v << ' ';
    dfs(n->r);
}

int main() {
    srand(time(0));
    ios::sync_with_stdio(0); fin.tie(0); fout.tie();
    int n, q, s = 0, a, b;
    char t;
    fin >> q >> a;
    while (q--) {
        fin >> t;
        if (t == 'I') {
            fin >> a >> b;
            insert(root, a, b);
        }
        else if (t == 'A') {
            fin >> a;
            fout << kth(root, a) << '\n';
        }
        else {
            fin >> a >> b;
            node* l, * r;
            tie(l, r) = split(root, b);
            node* ll, * rr;
            tie(ll, rr) = split(l, a - 1);
            if (t == 'R') {
                rr->rev ^= 1;
                root = join(join(ll, rr), r);
            }
            else
                root = join(ll, r);
        }
    }
    dfs(root);
}