-
Notifications
You must be signed in to change notification settings - Fork 3
/
range_module.cpp
83 lines (58 loc) · 1.84 KB
/
range_module.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
map<int, int>::iterator lower_bound2( map<int, int> &mp, int key) {
if(mp.empty())return mp.end();
auto it = mp.lower_bound(key);
if(it->first == key) return it;
if(it == mp.begin())return mp.end();
it--;
return it;
}
// Left and Right Inclusive
class RangeModule {
map<int, int> mp;
public:
RangeModule() {}
void addRange(int left, int right) {
removeRange(left, right);
auto it = lower_bound2(mp, left);
if(it!=mp.end() && it->second == left-1)
left = it->first;
if(mp.count(right+1)){
int t = right+1;
right = mp.find(t)->second;
mp.erase(t);
}
mp[left] = right;
}
bool queryRange(int left, int right) {
auto it = lower_bound2(mp, left);
return it!=mp.end() && it->second>=right;
}
void removeRange(int left, int right) {
if(mp.empty())return;
auto it = mp.lower_bound(left);
if(it!=mp.begin()) {
it--;
if(it->first < left){
if(it->second >= left) {
if(it->second >right)
mp[right+1] = it->second;
it->second = left - 1;
}
}
it++;
}
while(it!= mp.end() && it->first <=right) {
auto temp = it;
it++;
if(temp->second >right) mp[right+1] = temp->second;
mp.erase(temp);
}
}
};
/**
* 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);
*/