题目链接:http://vjudge.net/problem/18902/origin
题意:把一个区间翻转后拿出来加到序列的后面
代码:
#include <bits/stdc++.h>
#define sf scanf
#define pf printf
using namespace std;
const int maxn = 100000 + 50;
/** Splay */
int ch[maxn][2],fa[maxn],size[maxn],lazy[maxn];
int key[maxn],sroot,root,tot;
void Splay_Init(){
tot = 1;
root = sroot = 0;ch[sroot][0] = ch[sroot][1] = 0;size[0] = lazy[0] = 0;
}
int NewNode(int p,int k){
ch[tot][0] = ch[tot][1] = 0;
fa[tot] = p;
key[tot] = k;
size[tot] = 1;
lazy[tot] = 0;
return tot++;
}
void PushDown(int rt){
if(lazy[rt]){
swap(ch[rt][0],ch[rt][1]);
lazy[ch[rt][0]] = !lazy[ch[rt][0]];
lazy[ch[rt][1]] = !lazy[ch[rt][1]];
lazy[rt] = 0;
}
}
void PushUp(int rt){
size[rt] = size[ch[rt][0]] + size[ch[rt][1]] + 1;
}
void rotate(int rt,int kind){
int prt = fa[rt];
ch[prt][kind] = ch[rt][!kind];
fa[ch[rt][!kind]] = prt;
ch[fa[prt]][ ch[fa[prt]][1] == prt ] = rt;
fa[rt] = fa[prt];
ch[rt][!kind] = prt;
fa[prt] = rt;
PushUp(prt),PushUp(rt);
}
void Splay(int rt,int goal){
while(fa[rt] != goal){
if(fa[fa[rt]] == goal){
rotate(rt,ch[fa[rt]][1] == rt);
}
else{
int prt = fa[rt],kind = (ch[fa[prt]][1] == prt);
if(ch[prt][kind] == rt) rotate(rt,kind),rotate(rt,kind);
else rotate(rt,!kind),rotate(rt,kind);
}
}
if(fa[rt] == sroot) root = rt;
}
int Find(int rt,int k){
PushDown(rt);
if(size[ch[rt][0]] >= k) return Find(ch[rt][0],k);
else if(size[ch[rt][0]] + 1 == k) return rt;
else return Find(ch[rt][1],k - size[ch[rt][0]] - 1);
}
void DFS(int rt){
PushDown(rt);
if(ch[rt][0]) DFS(ch[rt][0]);
pf("%d\n",key[rt]);
if(ch[rt][1]) DFS(ch[rt][1]);
}
int Find_MAX(int rt){
PushDown(rt);
while(ch[rt][1]){
rt = ch[rt][1];
PushDown(rt);
}
return rt;
}
void solve(int l,int r,int n){
if(l == 1 && r == n){
lazy[root] = !lazy[root];
}
else{
int goal_rt,tmp_rt,p_rt;
if(l == 1){
r = Find(root,r + 1);
Splay(r,sroot);
goal_rt = ch[root][0];
}
else if(r == n){
l = Find(root,l - 1);
Splay(l,sroot);
goal_rt = ch[root][1];
}
else{
l = Find(root,l - 1);
r = Find(root,r + 1);
Splay(l,sroot);
Splay(r,root);
goal_rt = ch[ch[root][1]][0];
}
PushDown(goal_rt);
p_rt = fa[goal_rt];
size[p_rt] -= size[goal_rt];
ch[p_rt][ ch[p_rt][1] == goal_rt ] = sroot;
fa[goal_rt] = sroot;
tmp_rt = Find_MAX(root);
Splay(tmp_rt,sroot);
ch[root][1] = goal_rt;
fa[goal_rt] = root;
lazy[goal_rt] = !lazy[goal_rt];
}
}
int main(){
int n,m;
while(~sf("%d %d",&n,&m)){
Splay_Init();
for(int i = 0;i < n;++i){
ch[i][0] = 0;ch[i][1] = NewNode(i,i + 1);
size[i] = n - i + 1;
}size[0] = 0,root = 1;
for(int i = 0;i < m;++i){
int l,r;sf("%d %d",&l,&r);
solve(l,r,n);
}
DFS(root);
}
}