Cod sursa(job #2711384)

Utilizator BogdanTicuTicu Bogdan Valeriu BogdanTicu Data 24 februarie 2021 01:45:27
Problema Secv8 Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.36 kb
#include <bits/stdc++.h>

using namespace std;

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

const int MOD=1000*1000*1000+7;

struct node //treap
{
	node *l,*r;
	int val,priority,cnt;
	bool ok;

	node(int valoare,int pri){
		this->ok=0;
		this->val=valoare;
		this->priority=pri;
		this->l=NULL;
		this->r=NULL;
		this->cnt=1;
	}
};

node *rad;

int randomtime()
{
	return 1ll* rand() * rand() % MOD;	
}

void lazyup(node *&n)
{
	if(n && n->ok)
	{
		swap(n->l,n->r);
		n->ok=0;

		if(n->l)
			n->l->ok^=1;
		if(n->r)
			n->r->ok^=1;
	}
}


int getcnt(node *&n)
{
	if(n==NULL) return 0;
	return n->cnt;
}


void update(node *&n)
{
	if(n==NULL)
		return;
	n->cnt=1+getcnt(n->l)+getcnt(n->r);
}


void join(node *&n,node *&tr1,node *&tr2)
{
	lazyup(tr1);	
	lazyup(tr2);
	if(tr1==NULL || tr2==NULL)
	{
		if(tr1==NULL) n=tr2;
		else n=tr1;
	}
	else if(tr1->priority > tr2->priority)
	{
		n=tr1;
		join(n->r,tr1->r,tr2);
	}
	else
	{
		n=tr2;
		join(n->l,tr1,tr2->l);
	}
	update(n);
}


void split(node *&n,node *&tr1,node *&tr2,int key,int add)
{
	if(n==NULL)
	{
		tr1=NULL;
		tr2=NULL;
		return;
	}

	lazyup(n);
	int aux=add+getcnt(n->l)+1;

	if(aux<=key)
	{
		tr1=n;
		split(n->r,tr1->r,tr2,key,aux);
	}
	else
	{
		tr2=n;
		split(n->l,tr1,tr2->l,key,add);
	}
	update(n);
}

void insert(node *&n,node *new_node,int pos)
{
	node *tr1,*tr2;
	split(n,tr1,tr2,pos-1,0);
	join(tr1,tr1,new_node);
	join(n,tr1,tr2);
}

void erase(node *&n,int x,int y)
{
	node *tr1=NULL;
	node *tr2=NULL;
	node *tr3=NULL;
	split(n,tr1,tr3,y,0);
	split(tr1,tr1,tr2,x-1,0);
	join(n,tr1,tr3);
}

void reverse(node *&n,int x,int y)
{
	node *tr1=NULL;	
	node *tr2=NULL;	
	node *tr3=NULL;

	tr2->ok ^=1;
	join(n,tr1,tr2);
	join(n,n,tr3);
}


int access(node *n,int pos)
{	
	node *tr1=NULL;	
	node *tr2=NULL;	
	node *tr3=NULL;	
	split(n,tr1,tr3,pos,0);
	split(tr1,tr1,tr2,pos-1,0);

	int ans=tr2->val;
	join(n,tr1,tr2);
	join(n,n,tr3);
	return ans;
}


void afisare(node *&n)
{
	if(n==NULL)
		return;
	lazyup(n);
	afisare(n->l);
	out<<n->val<<" ";
	afisare(n->r);
}
int main()
{
	srand(time(NULL));
	int t,x,y;
	in>>t>>x;
	while(t--)
	{
		char code;
		in>>code;
		if(code=='I')
		{
			in>>y;
			node *new_node=new node(y,rand());
			insert(rad,new_node,x);
		}
		if(code=='A')
			out<<access(rad,x)<<"\n";
		if(code=='R')
		{
			in>>y;
			reverse(rad,x,y);
		}
		if(code=='D')
		{
			in>>y;
			erase(rad,x,y);
		}
	}
	afisare(rad);
	return 0;
}