forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
103 lines (87 loc) · 2.57 KB
/
Solution.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
98
99
100
101
102
103
class Node {
Node left;
Node right;
int add;
boolean v;
}
class SegmentTree {
private Node root = new Node();
public SegmentTree() {
}
public void modify(int left, int right, int v) {
modify(left, right, v, 1, (int) 1e9, root);
}
public void modify(int left, int right, int v, int l, int r, Node node) {
if (l >= left && r <= right) {
node.v = v == 1;
node.add = v;
return;
}
pushdown(node);
int mid = (l + r) >> 1;
if (left <= mid) {
modify(left, right, v, l, mid, node.left);
}
if (right > mid) {
modify(left, right, v, mid + 1, r, node.right);
}
pushup(node);
}
public boolean query(int left, int right) {
return query(left, right, 1, (int) 1e9, root);
}
public boolean query(int left, int right, int l, int r, Node node) {
if (l >= left && r <= right) {
return node.v;
}
pushdown(node);
int mid = (l + r) >> 1;
boolean v = true;
if (left <= mid) {
v = v && query(left, right, l, mid, node.left);
}
if (right > mid) {
v = v && query(left, right, mid + 1, r, node.right);
}
return v;
}
public void pushup(Node node) {
node.v = node.left != null && node.left.v && node.right != null && node.right.v;
}
public void pushdown(Node node) {
if (node.left == null) {
node.left = new Node();
}
if (node.right == null) {
node.right = new Node();
}
if (node.add != 0) {
node.left.add = node.add;
node.right.add = node.add;
node.left.v = node.add == 1;
node.right.v = node.add == 1;
node.add = 0;
}
}
}
class RangeModule {
private SegmentTree tree = new SegmentTree();
public RangeModule() {
}
public void addRange(int left, int right) {
tree.modify(left, right - 1, 1);
}
public boolean queryRange(int left, int right) {
return tree.query(left, right - 1);
}
public void removeRange(int left, int right) {
tree.modify(left, right - 1, -1);
}
}
/**
* Your RangeModule object will be instantiated and called as such:
* RangeModule obj = new RangeModule();
* obj.addRange(left,right);
* boolean param_2 = obj.queryRange(left,right);
* obj.removeRange(left,right);
*/