-
Notifications
You must be signed in to change notification settings - Fork 156
/
2072 - Cut and Paste.cpp
93 lines (83 loc) · 2.04 KB
/
2072 - Cut and Paste.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
/*
Problem Name: Cut and Paste
Problem Link: https://cses.fi/problemset/task/2072
Author: Sachin Srivastava (mrsac7)
*/
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define endl '\n'
struct node {
node *left, *right;
int weight, size;
char value;
node(char v) {
left = right = NULL;
weight = rand();
size = 1;
value = v;
}
};
int size(node *treap) {
if (treap == NULL) return 0;
return treap->size;
}
void split(node *treap, node *&left, node *&right, int k) {
if (treap == NULL) {
left = right = NULL;
}
else {
if (size(treap->left) < k) {
split(treap->right, treap->right, right, k - size(treap->left)-1);
left = treap;
}
else {
split(treap->left, left, treap->left, k);
right = treap;
}
treap->size = size(treap->left) + size(treap->right) + 1;
}
}
void merge(node *&treap, node *left, node *right) {
if (left == NULL) treap = right;
else if(right == NULL) treap = left;
else {
if (left->weight < right->weight) {
merge(left->right, left->right, right);
treap = left;
}
else {
merge(right->left, left, right->left);
treap = right;
}
treap->size = size(treap->left) + size(treap->right) + 1;
}
}
void print(node *treap) {
if (treap == NULL) return;
print(treap->left);
cout << treap->value;
print(treap->right);
}
signed main(){
cin.tie(0)->sync_with_stdio(0);
#ifdef LOCAL
freopen("input.txt", "r" , stdin);
freopen("output.txt", "w", stdout);
#endif
node *treap = 0;
int n, m; cin >> n >> m;
string s; cin >> s;
for (auto i: s) {
merge(treap, treap, new node(i));
}
while (m--) {
int x, y; cin >> x >> y;
node *A, *B, *C, *D;
split(treap, A, B, x - 1);
split(B, D, C, y - x + 1);
merge(treap, A, C);
merge(treap, treap, D);
}
print(treap);
}