-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathIndexedTreeTest.java
97 lines (84 loc) Β· 2.94 KB
/
IndexedTreeTest.java
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
package IndexedTree;
import java.util.Arrays;
public class IndexedTreeTest {
public static void main(String[] args) {
int[] inputs = {0, 3, 2, 4, 5, 1, 6, 2, 7};
// depth 3 => leaf 8κ°
IndexedTree it = new IndexedTree(inputs);
System.out.println(it);
it.makeTree(1, 1, it.leafSize);
System.out.println(it);
System.out.println(it.query(1, 1, it.leafSize, 3, 7));
// index 3μ 4 -> 3μΌλ‘ λ°κΎΈκΈ°
int targetIndex = 3;
int targetValue = 3;
int diff = targetValue - it.nums[targetIndex];
it.update(1, 1, it.leafSize, 3, diff);
it.nums[targetIndex] = targetValue;
System.out.println(it);
}
}
class IndexedTree {
int[] tree;
int[] nums;
int leafSize, depth;
public IndexedTree(int[] nums){
this.nums = nums;
this.depth = 0;
while (Math.pow(2, depth) < nums.length - 1) {
this.depth ++;
}
this.leafSize = (int) Math.pow(2, depth);
this.tree = new int[(int) Math.pow(2, depth + 1)];
}
// λ΄λΆ λ
Έλμ κ°μ μ±μμ€λ€.
public int makeTree(int node, int left, int right){
// leafμ λλ¬νμ λ
if (left == right) {
if (left <= nums.length - 1) {
return tree[node] = nums[left];
} else {
return tree[node] = 0;
}
}
// λ΄λΆ λ
ΈλμΌ κ²½μ°
int mid = (left + right) / 2;
tree[node] = makeTree(node * 2, left, mid);
tree[node] += makeTree(node * 2 + 1, mid + 1, right);
return tree[node];
}
// μνλ ꡬκ°μ ν© or λ¬Έμ μ λ΅μ ꡬνλ€.
public int query(int node, int left, int right, int qLeft, int qRight){
if (qRight < left || qLeft > right){ // κ΄λ ¨μ΄ μλ κ²½μ°
return 0;
} else if (qLeft <= left && right <= qRight) { // 쿼리μ μμ ν μνλ κ²½μ°
return tree[node];
} else { // κ·Έ μΈ : μ 맀νκ² κ±Έμ³μλ κ²½μ°
int mid = (left + right) / 2;
return query(node * 2, left, mid, qLeft, qRight)
+ query(node * 2 + 1,mid + 1, right, qLeft, qRight);
}
}
// νΉμ κ°μ κ°±μ νλ€.
public void update(int node, int left, int right, int index, int diff){
if (index < left || right < index) {
return;
} else {
tree[node] += diff;
if (left != right) {
int mid = (left + right) / 2;
update(node * 2, left, mid, index, diff);
update(node * 2 + 1, mid + 1, right, index, diff);
}
}
}
@Override
public String toString() {
return "IndexedTree{" +
"tree=" + Arrays.toString(tree) +
", nums=" + Arrays.toString(nums) +
", leafSize=" + leafSize +
", depth=" + depth +
'}';
}
}