forked from wisdompeak/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path715.Range-Module_segTree.cpp
88 lines (78 loc) · 2.39 KB
/
715.Range-Module_segTree.cpp
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
class RangeModule {
class SegTree
{
public:
int start, end;
bool status;
SegTree* left;
SegTree* right;
SegTree(int a, int b, bool T):start(a),end(b),status(T),left(NULL),right(NULL){}
void remove(SegTree* &node)
{
if (node==NULL) return;
remove(node->left);
remove(node->right);
delete node;
node = NULL;
return;
}
void setStatus(int a, int b, bool T)
{
if (a<=start && b>=end) // bottom condition 1: [a,b)>[start,end)
{
remove(left);
remove(right);
status = T;
return;
}
if (a>=end || b<=start) // bottom condition 2: [a,b) do not intersect with [start,end)
return;
int mid = start+(end-start)/2;
if (left==NULL) // no children? create them!
{
left = new SegTree(start,mid,status);
right = new SegTree(mid,end,status);
}
left->setStatus(a,b,T);
right->setStatus(a,b,T);
status =left->status && right->status;
}
bool getStatus(int a, int b)
{
if (a<=start && b>=end) // bottom condition 1: [a,b)>[start,end)
return status;
if (a>=end || b<=start) // bottom condition 2: [a,b) do not intersect with [start,end)
return true;
if (left==NULL)
return status;
int mid = start+(end-start)/2;
bool L = left->getStatus(a,b);
bool R = right->getStatus(a,b);
return L&&R;
}
};
public:
SegTree root = SegTree(0,1e9,false);
RangeModule()
{
}
void addRange(int left, int right)
{
root.setStatus(left,right,true);
}
bool queryRange(int left, int right)
{
return root.getStatus(left,right);
}
void removeRange(int left, int right)
{
root.setStatus(left,right,false);
}
};
/**
* Your RangeModule object will be instantiated and called as such:
* RangeModule obj = new RangeModule();
* obj.addRange(left,right);
* bool param_2 = obj.queryRange(left,right);
* obj.removeRange(left,right);
*/