forked from mrsac7/CSES-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2073 - Substring Reversals.cpp
More file actions
114 lines (102 loc) · 2.36 KB
/
2073 - Substring Reversals.cpp
File metadata and controls
114 lines (102 loc) · 2.36 KB
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
// Substring Reversals
//
// Problem name: Substring Reversals
// Problem Link: https://cses.fi/problemset/task/2073
// Author: Bernardo Archegas (https://codeforces.com/profile/Ber)
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
mt19937 rng((int) chrono::steady_clock::now().time_since_epoch().count());
const int MOD = 1e9 + 7;
const int MAXN = 2e6 + 5;
const ll INF = 2e18;
struct node {
node *L, *R;
int prio, sz;
char c;
bool rev;
node (char _c) {
L = 0, R = 0, prio = rng(), sz = 1, c = _c, rev = false;
}
};
int size(node *treap) {
if (!treap) return 0;
return treap->sz;
}
void push(node *treap) {
if (treap && treap->rev) {
treap->rev = false;
swap(treap->L, treap->R);
if (treap->L) treap->L->rev ^= true;
if (treap->R) treap->R->rev ^= true;
}
}
void recalc(node *&treap) {
if (!treap) return;
treap->sz = size(treap->L) + size(treap->R) + 1;
}
void split(node *treap, node *&L, node *&R, int k) {
if (!treap) {
L = R = 0;
}
else {
push(treap);
if (size(treap->L) >= k) {
split(treap->L, L, treap->L, k);
R = treap;
}
else {
split(treap->R, treap->R, R, k - size(treap->L) - 1);
L = treap;
}
recalc(treap);
}
}
void merge(node *&treap, node *L, node *R) {
if (!L) treap = R;
else if (!R) treap = L;
else {
push(L), push(R);
if (L->prio > R->prio) {
merge(L->R, L->R, R);
treap = L;
}
else {
merge(R->L, L, R->L);
treap = R;
}
recalc(treap);
}
}
void print(node *treap) {
if (!treap) return;
push(treap);
print(treap->L);
cout << treap->c;
print(treap->R);
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n, m, l, r;
string s;
cin >> n >> m >> s;
node *root = 0;
for (int i = 0; i < n; i++) {
merge(root, root, new node(s[i]));
}
for (int i = 0; i < m; i++) {
cin >> l >> r;
node *a, *b, *c;
split(root, a, b, l - 1);
split(b, b, c, r - l + 1);
b->rev ^= true;
merge(root, a, b);
merge(root, root, c);
}
print(root);
cout << '\n';
return 0;
}