Cod sursa(job #2702297)

Utilizator Stefan_PiscuPiscu Stefan Constantin Stefan_Piscu Data 3 februarie 2021 17:13:02
Problema Secv8 Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.98 kb
#include <bits/stdc++.h>
using namespace std;

#define cin fin
#define cout fout

ifstream cin("secv8.in");
ofstream cout("secv8.out");

struct nod{
	nod *l=NULL, *r=NULL;
	int val, pri;
	int w;
	bool rv;
	nod(int x): val(x), pri(rand()), w(1), rv(0) {};
	void upd();
};
nod *root=0;
int cnt (nod *t) {
		return t?t->w:0;
}
void nod::upd(){
	w=1+cnt(l)+cnt(r);
	if(rv){
		swap(l, r);
		if(l) l->rv^=1;
		if(r) r->rv^=1;
		rv=0;
	}
}
pair<nod*, nod*> split(nod *t, int poz){
	if(t==NULL) return {NULL, NULL};
	t->upd();
	if(poz<=cnt(t->l)){
		auto r=split(t->l, poz);
		t->l=r.second, t->upd();
		return {r.first, t};
	}
	else{
		auto r=split(t->r, poz-cnt(t->l)-1);
		t->r=r.first, t->upd();
		return {t, r.second};
	}
}

nod* join(nod *l, nod *r){
	if(!l) return r;
	if(!r) return l;
	l->upd(), r->upd();
	if(l->pri>r->pri){
		l->r=join(l->r, r), l->upd();
		return l;
	}
	else{
		r->l=join(l, r->l); r->upd();
		return r;
	}
}

void show(nod *t){
	if(t==0) return;
	t->upd();
	show(t->l);
	cout<<t->val<<" ";
	show(t->r);
}

nod* add(nod* t, int x, int poz){
	auto aux=split(t, poz-1);
	nod *aux2=new nod(x);
	return join(join(aux.first, aux2), aux.second);
}

nod* erase(nod* t, int l, int r){
	auto aux=split(t, r);	
	auto aux2=split(aux.first, l-1);
	delete(aux2.second);
	return join(aux2.first, aux.second);
}

nod* reverse(nod *t, int l, int r){
	auto aux=split(t, r);
	auto aux2=split(aux.first, l-1);
	aux2.second->rv^=1;
	return join(join(aux2.first, aux2.second), aux.second);
}

int get(nod *t, int poz){
	t->upd();
	if(poz-1==cnt(t->l)) return t->val;
	if(poz<=cnt(t->l)) return get(t->l, poz);
	return get(t->r, poz-cnt(t->l)-1);
}



int main(){
	int t, trs;
	cin>>t>>trs;
	while(t--){
		char tip;
		cin>>tip;
		int a, b;
		if(tip=='I'){
			cin>>a>>b;
			root=add(root, b, a);
		}
		else if(tip=='A'){
			cin>>a;
			cout<<get(root, a)<<"\n";
		}
		else if(tip=='R'){
			cin>>a>>b;
			root=reverse(root, a, b);
		}
		else{
			cin>>a>>b;
			root=erase(root, a, b);
		}
	}
	show(root);
	cout<<"\n";
	return 0;
}