-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy path*Treaps.java
More file actions
118 lines (97 loc) · 2.14 KB
/
*Treaps.java
File metadata and controls
118 lines (97 loc) · 2.14 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
115
116
117
118
class Treaps {
static final Random rand = new Random();
static node root;
static long getMin(int l, int r) {
node[] b = split(root, r + 1);
node[] a = split(b[0], l);
long out = a[1].min;
b[0] = merge(a[0], a[1]);
root = merge(b[0], b[1]);
return out;
}
static long getSum(int l, int r) {
node[] b = split(root, r + 1);
node[] a = split(b[0], l);
long out = a[1].sum;
b[0] = merge(a[0], a[1]);
root = merge(b[0], b[1]);
return out;
}
static void add(int l, int r, long add) {
node[] b = split(root, r + 1);
node[] a = split(b[0], l);
addNode(a[1], add);
b[0] = merge(a[0], a[1]);
root = merge(b[0], b[1]);
}
static node merge(node a, node b) {
if(a == null) return b;
if(b == null) return a;
push(a);
push(b);
if(a.prior < b.prior) {
a.r = merge(a.r, b);
update(a);
return a;
}
else{
b.l = merge(a, b.l);
update(b);
return b;
}
}
static node[] split(node a, int numLeft) {
if(a == null) return new node[2];
push(a);
if(numLeft <= size(a.l)) {
node[] get = split(a.l, numLeft);
a.l = get[1];
update(a);
return new node[] {get[0], a};
}
else {
node[] get = split(a.r, numLeft - (size(a.l) + 1));
a.r = get[0];
update(a);
return new node[] {a, get[1]};
}
}
static void update(node in) {
in.size = 1 + size(in.l) + size(in.r);
in.sum = in.val + sum(in.l) + sum(in.r);
in.min = min(in.val, min(min(in.l), min(in.r)));
}
static void push(node in) {
if(in.l != null) addNode(in.l, in.lazy);
if(in.r != null) addNode(in.r, in.lazy);
in.lazy = 0;
}
static void addNode(node in, long add) {
in.val += add;
in.sum += add * in.size;
in.min += add;
in.lazy += add;
}
static long min(node in) {
return in == null ? Long.MAX_VALUE : in.min;
}
static long sum(node in) {
return in == null ? 0 : in.sum;
}
static int size(node in) {
return in == null ? 0 : in.size;
}
static class node{
int prior, size;
long val, sum, min, lazy;
node l, r;
node(long vv){
min = sum = val = vv;
prior = rand.nextInt();
size = 1;
}
}
static long min(long a, long b) {
return a < b ? a : b;
}
}