注意spaly的时候pushdown两遍,注意建立虚拟节点
#include <bits/stdc++.h>
const int maxn = 1e5 + 10;
using namespace std;
struct Node {
Node *ch[2];
int v, s, lazy;
Node() { ch[0] = ch[1] = NULL; v = s = lazy = 0; }
int cmp(int x) { if (x == ch[0]->s+1) return -1; return x < ch[0]->s+1 ? 0 : 1; }
void maintain() { s = ch[0]->s+ch[1]->s+1; }
void pushdown() {
if (!lazy) return;
swap(ch[0], ch[1]);
ch[0]->lazy = !(ch[0]->lazy);
ch[1]->lazy = !(ch[1]->lazy);
lazy = 0;
}
};
Node *null = new Node();
Node *newnode(int v) {
Node *node = new Node();
node->ch[0] = node->ch[1] = null;
node->v = v;
node->s = 1;
node->lazy = 0;
return node;
}
void rotate(Node *&o, int d) {
Node *k = o->ch[d^1]; o->ch[d^1] = k->ch[d]; k->ch[d] = o;
o->maintain(); k->maintain(); o = k;
}
void splay(Node *&o, int k) {
o->pushdown();
int d = o->cmp(k);
if (d == 1) k -= o->ch[0]->s + 1;
if (d != -1) {
Node *p = o->ch[d];
p->pushdown();
int d2 = p->cmp(k);
int k2 = (d2 == 0 ? k : k - p->ch[0]->s - 1);
if (d2 != -1) {
splay(p->ch[d2], k2);
if (d == d2) rotate(o, d^1); else rotate(o->ch[d], d);
}
rotate(o, d^1);
}
}
Node *merge(Node *left, Node *right) {
splay(left, left->s);
left->ch[1] = right;
left->maintain();
return left;
}
void split(Node *o, int k, Node *&left, Node *&right) {
splay(o, k);
left = o;
right = o->ch[1];
o->ch[1] = null;
left->maintain();
}
Node *root;
void init() { root = newnode(0); }
void build(Node *&o, int l, int r) {
if (l > r) return;
int mid = (l + r)>>1;
o = newnode(mid);
build(o->ch[0], l, mid-1);
build(o->ch[1], mid+1, r);
o->maintain();
}
void output(Node *o) {
if (o == null) return;
o->pushdown();
output(o->ch[0]);
if (o->v != 0) printf("%d\n", o->v);
output(o->ch[1]);
}
int n, m;
int main() {
scanf("%d%d", &n, &m);
init();
build(root->ch[1], 1, n);
root->maintain();
while (m--) {
int a, b;
scanf("%d%d", &a, &b);
Node *left, *right, *mid, *t;
split(root, a, left, t);
split(t, b-a+1, mid, right);
mid->lazy ^= 1;
root = merge(merge(left, right), mid);
}
output(root);
return 0;
}