forked from jakobkogler/Algorithm-DataStructures
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSegmentTree.java
More file actions
71 lines (61 loc) · 1.83 KB
/
Copy pathSegmentTree.java
File metadata and controls
71 lines (61 loc) · 1.83 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
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
public class SegmentTree
{
private ArrayList<Integer> data;
private int n;
public SegmentTree(List<Integer> arr) {
n = arr.size();
data = new ArrayList<Integer>(2 * n);
for (int idx = 0; idx < n; idx++) {
data.add(0);
}
for (int idx = 0; idx < n; idx++) {
data.add(arr.get(idx));
}
for (int idx = n-1; idx > 0; idx--) {
data.set(idx, Math.min(data.get(2*idx), data.get(2*idx+1)));
}
}
public void update(int idx, int value) {
idx += n;
data.set(idx, value);
while (idx > 1) {
idx /= 2;
data.set(idx, Math.min(data.get(2*idx), data.get(2*idx+1)));
}
}
public int minimum(int left, int right) {
left += n;
right += n;
int min = Integer.MAX_VALUE;
while (left < right) {
if ((left & 1) == 1) {
min = Math.min(min, data.get(left));
left++;
}
if ((right & 1) == 1) {
right--;
min = Math.min(min, data.get(right));
}
left >>= 1;
right >>= 1;
}
return min;
}
public static void main(String[] args) {
SegmentTree st = new SegmentTree(Arrays.asList(5, 2, 3, 1, 4));
for (int i = 0; i < 5; i++) {
System.out.println(st.minimum(i, i+1));
}
System.out.println(st.minimum(i, i+1));
System.out.println(st.minimum(1, 4));
st.update(3, 10);
System.out.println(st.minimum(1, 4));
System.out.println(st.minimum(0, 5));
st.update(4, 0);
System.out.println(st.minimum(1, 4));
System.out.println(st.minimum(0, 5));
}
}