-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSegmentsTreeSimple.java
More file actions
68 lines (63 loc) · 1.11 KB
/
SegmentsTreeSimple.java
File metadata and controls
68 lines (63 loc) · 1.11 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
public class SegmentsTreeSimple {
int n;
int[] min;
int[] max;
int size;
public SegmentsTreeSimple(int n) {
this.n = n;
size = 1;
while (size <= n) {
size *= 2;
}
min = new int[2 * size];
max = new int[2 * size];
}
void set(int index, int value) {
int i = size + index;
min[i] = max[i] = value;
while (i > 1) {
i /= 2;
min[i] = Math.min(min[2 * i], min[2 * i + 1]);
max[i] = Math.max(max[2 * i], max[2 * i + 1]);
}
}
int get(int index) {
return min[size + index];
}
int getMax(int from, int to) {
from += size;
to += size;
int res = Integer.MIN_VALUE;
while (from < to) {
if (from % 2 == 1) {
res = Math.max(res, max[from]);
from++;
}
if (to % 2 == 1) {
to--;
res = Math.max(res, max[to]);
}
from /= 2;
to /= 2;
}
return res;
}
int getMin(int from, int to) {
from += size;
to += size;
int res = Integer.MAX_VALUE;
while (from < to) {
if (from % 2 == 1) {
res = Math.min(res, min[from]);
from++;
}
if (to % 2 == 1) {
to--;
res = Math.min(res, min[to]);
}
from /= 2;
to /= 2;
}
return res;
}
}