-
Notifications
You must be signed in to change notification settings - Fork 174
/
Copy pathCut and Paste.cpp
121 lines (102 loc) · 2.19 KB
/
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
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
#include <bits/stdc++.h>
using namespace std;
const int maxN = 2e5+5;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
uniform_int_distribution<int> dist(1, (int) 2e9);
struct Node {
char ch;
int prior, sz;
Node *l, *r;
Node(){}
Node(char c, int p){
prior = p;
ch = c;
sz = 1;
l = r = nullptr;
}
};
int N, M, a, b;
char S[maxN];
Node *root;
int sz(Node *t){ return t ? t->sz : 0; }
void pull(Node *t){
if(!t) return;
t->sz = sz(t->l) + sz(t->r) + 1;
}
void push(Node *t){
if(!t) return;
}
Node* merge(Node *x, Node *y){
if(!x || !y) return x ? x : y;
push(x); push(y);
if(x->prior < y->prior){
x->r = merge(x->r, y);
pull(x);
return x;
} else {
y->l = merge(x, y->l);
pull(y);
return y;
}
}
pair<Node*,Node*> split(Node *x, int k){
if(!x) return {nullptr, nullptr};
pair<Node*,Node*> y = {nullptr, nullptr};
push(x);
if(k <= sz(x->l)){
y = split(x->l, k);
x->l = y.second;
pull(x);
y.second = x;
} else {
y = split(x->r, k-sz(x->l)-1);
x->r = y.first;
pull(x);
y.first = x;
}
return y;
}
void heapify(Node *t){
if(!t) return;
Node *mx = t;
if(t->l && t->l->prior > mx->prior) mx = t->l;
if(t->r && t->r->prior > mx->prior) mx = t->r;
if(mx != t){
swap(t->prior, mx->prior);
heapify(mx);
}
}
Node* build(int x, int k){
if(k == 0) return nullptr;
int mid = k/2;
Node *t = new Node(S[x+mid], dist(rng));
t->l = build(x, mid);
t->r = build(x+mid+1, k-mid-1);
heapify(t);
pull(t);
return t;
}
void cut(int x, int k){
pair<Node*,Node*> y, z;
y = split(root, x-1);
z = split(y.second, k);
y.second = merge(z.second, z.first);
root = merge(y.first, y.second);
}
void print(Node *t){
if(!t) return;
push(t);
print(t->l);
printf("%c", t->ch);
print(t->r);
}
int main(){
scanf("%d %d %s", &N, &M, S);
root = build(0, N);
for(int i = 0; i < M; i++){
scanf("%d %d", &a, &b);
int len = (b-a+1);
cut(a, len);
}
print(root);
}