forked from indy256/codelibrary
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Tree2d.java
52 lines (46 loc) · 1.58 KB
/
Tree2d.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
package structures;
public class Tree2d {
Treap.Node[] t;
public Tree2d(int n) {
t = new Treap.Node[2 * n];
}
public long query(int x1, int x2, int y1, int y2) {
long res = 0;
for (x1 += t.length / 2, x2 += t.length / 2; x1 <= x2; x1 = (x1 + 1) >> 1, x2 = (x2 - 1) >> 1) {
if ((x1 & 1) != 0) {
Treap.TreapAndResult treapAndResult = Treap.query(t[x1], y1, y2);
t[x1] = treapAndResult.treap;
res += treapAndResult.sum;
}
if ((x2 & 1) == 0) {
Treap.TreapAndResult treapAndResult = Treap.query(t[x2], y1, y2);
t[x2] = treapAndResult.treap;
res += treapAndResult.sum;
}
}
return res;
}
public void insert(int x, int y, int value) {
x += t.length / 2;
for (; x > 0; x >>= 1) t[x] = Treap.insert(t[x], y, value);
}
public void modify(int x1, int x2, int y1, int y2, int delta) {
for (x1 += t.length / 2, x2 += t.length / 2; x1 <= x2; x1 = (x1 + 1) >> 1, x2 = (x2 - 1) >> 1) {
if ((x1 & 1) != 0) {
t[x1] = Treap.modify(t[x1], y1, y2, delta);
}
if ((x2 & 1) == 0) {
t[x2] = Treap.modify(t[x2], y1, y2, delta);
}
}
}
// Usage example
public static void main(String[] args) {
Tree2d t = new Tree2d(10);
t.insert(1, 5, 3);
t.insert(3, 3, 2);
t.insert(2, 6, 1);
t.modify(0, 9, 0, 9, 1);
System.out.println(t.query(0, 9, 0, 9));
}
}