-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathTWIST (insert via merge).cpp
145 lines (119 loc) · 2.73 KB
/
TWIST (insert via merge).cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
// https://www.spoj.com/problems/TWIST/
// Time complexity: O(min(N*log(N),M*log(N)), can be done in O(min(N,M*log(N))
// Space complexity: O(N)
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <utility>
using namespace std;
typedef struct Node *pnode;
struct Node {
int key, prior, cnt;
bool rev;
pnode l, r;
Node(int key) : key(key), prior(rand()), cnt(1), rev(false), l(nullptr), r(nullptr) {}
};
struct Treap {
private:
pnode root;
void clear(pnode t) {
if (t) {
clear(t->l);
clear(t->r);
delete t;
}
}
int cnt(pnode t) {
return t ? t->cnt : 0;
}
void updCnt(pnode t) {
if (t) {
t->cnt = 1 + cnt(t->l) + cnt(t->r);
}
}
void pushLazy(pnode t) {
if (t && t->rev) {
t->rev = false;
swap(t->l, t->r);
if (t->l) {
t->l->rev ^= 1;
}
if (t->r) {
t->r->rev ^= 1;
}
}
}
void split(pnode t, pnode &l, pnode &r, int key, int add = 0) {
if (!t) {
return void(l = r = nullptr);
}
pushLazy(t);
int curKey = add + cnt(t->l);
if (key <= curKey) {
split(t->l, l, t->l, key, add), r = t;
} else {
split(t->r, t->r, r, key, add + 1 + cnt(t->l)), l = t;
}
updCnt(t);
}
void merge(pnode &t, pnode l, pnode r) {
pushLazy(l);
pushLazy(r);
if (!l || !r) {
t = l ? l : r;
} else if (l->prior < r->prior) {
merge(r->l, l, r->l), t = r;
} else {
merge(l->r, l->r, r), t = l;
}
updCnt(t);
}
void insert(pnode &t, pnode it) {
merge(t, t, it);
}
void reverse(pnode &t, int l, int r) {
pnode t1, t2, t3;
split(t, t1, t2, l - 1);
split(t2, t2, t3, r - l + 1);
t2->rev ^= true;
merge(t, t1, t2);
merge(t, t, t3);
}
void LDR(pnode t) {
if (t) {
pushLazy(t);
LDR(t->l);
printf("%d ", t->key);
LDR(t->r);
}
}
public:
Treap() : root(nullptr) {
srand(time(nullptr));
}
~Treap() {
clear(this->root);
}
void insert(int key) {
insert(this->root, new Node(key));
}
void reverse(int l, int r) {
reverse(this->root, l, r);
}
void LDR() {
LDR(this->root);
}
};
int main() {
int N, M, l, r;
scanf("%d %d", &N, &M);
Treap T;
for (int i = 1; i <= N; ++i) {
T.insert(i);
}
while (M--) {
scanf("%d %d", &l, &r);
T.reverse(l, r);
}
return T.LDR(), 0;
}