题意:根据m条指令改变排列1 2 3 4 … n ,每条指令(a, b)表示取出第a~b个元素,反转后添加到排列尾部
分析:用一个可分裂合并的序列来表示整个序列,截取一段可以用两次分裂一次合并实现,粘贴到末尾可以用一次合并实现。
翻转可以采用在每个结点上做标记的方法,flip = 1意味着将这棵子树翻转,可以类似线段树用一个pushdown()实现标记向下传递。
可以发现当前排列就是伸展树的中序遍历序列。中序遍历打印结果即可。
注意代码中设置了虚拟首结点0的技巧。
代码如下:
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <vector>
using namespace std; struct Node {
Node* ch[];
int r, v, s;
int flip;
Node(int vv): v(vv) {
r = rand();
s = ;
ch[] = ch[] = NULL;
flip = ;
}
bool cmp(const int &x) const {
if(x == v) return -;
return x < v ? : ;
}
void maintain() {
s = ;
if(ch[] != NULL) s += ch[]->s;
if(ch[] != NULL) s += ch[]->s;
}
void pushdown() {
if(flip) {
flip = ;
swap(ch[], ch[]);
if(ch[] != NULL) ch[]->flip = !ch[]->flip;
if(ch[] != NULL) ch[]->flip = !ch[]->flip;
}
}
};
void rotate(Node* &o, int d) {
Node* k = o->ch[d^]; o->ch[d^] = k->ch[d]; k->ch[d] = o;
o->maintain(); k->maintain(); o = k;
}
void insert(Node* &o, int x) {
if(o == NULL) o = new Node(x);
else {
int d = o->cmp(x);
insert(o->ch[d], x);
if(o->ch[d]->r > o->r) rotate(o, d^);
}
o->maintain();
} void splay(Node* &o, int k) {
o->pushdown();
int s = o->ch[] == NULL ? : o->ch[]->s;
int d = k <= s ? : (k == s+ ? - : );
if(d == ) k -= s+;
if(d != -) {
splay(o->ch[d], k);
rotate(o, d^);
}
} Node* merge(Node* left, Node* right) {
splay(left, left->s);
left->ch[] = right;
left->maintain();
return left;
} void split(Node* o, int k , Node* &left, Node* &right) {
splay(o, k);
left = o;
right = o->ch[];
o->ch[] = NULL;
left->maintain();
}
vector<int> seq;
void dfs(Node* o) {
if(o == NULL) return;
o->pushdown();
dfs(o->ch[]);
if(o->v) {
//printf("%d ", o->v);
seq.push_back(o->v);
}
dfs(o->ch[]);
}
int n, m;
int main() {
cin >> n >> m;
Node* root = new Node(); //虚拟首结点0,方便分裂操作
for(int i = ; i <= n; i++) insert(root, i);
while(m--) {
int a, b;
cin >> a >> b;
Node *left, *mid, *right, *o;
split(root, a, left, o);
split(o, b-a+, mid, right);
mid->flip ^= ;
root = merge(merge(left, right), mid);
}
dfs(root);
for(int i = 0; i < seq.size(); i++) cout<<seq[i]<<endl;
return ;
}