- Identify the ordered answer range or sorted search domain.
- Write a predicate whose truth changes only once.
- Move the appropriate boundary after each midpoint check and return the final feasible position.
Code notes
- 52 lines of C++ from the credited upstream file 715-2.cpp.
- The implementation visibly relies on ordered lookup.
- No explicit loop blocks detected.
Complexity
Multiply the logarithmic number of midpoint checks by the cost of one predicate evaluation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class RangeModule {2 public:3 void addRange(int left, int right) {4 const auto [l, r] = getOverlapRanges(left, right);5 if (l == r) { 6 ranges[left] = right; 7 return;8 }9 10 auto last = r;11 const int newLeft = min(l->first, left);12 const int newRight = max((--last)->second, right);13 ranges.erase(l, r);14 ranges[newLeft] = newRight; 15 }16 17 bool queryRange(int left, int right) {18 auto it = ranges.upper_bound(left);19 return it != ranges.begin() && (--it)->second >= right;20 }21 22 void removeRange(int left, int right) {23 const auto [l, r] = getOverlapRanges(left, right);24 if (l == r) 25 return;26 27 auto last = r;28 const int newLeft = min(l->first, left);29 const int newRight = max((--last)->second, right);30 ranges.erase(l, r);31 32 if (newLeft < left)33 ranges[newLeft] = left;34 if (right < newRight)35 ranges[right] = newRight;36 }37 38 private:39 using IT = map<int, int>::iterator;40 map<int, int> ranges;41 42 pair<IT, IT> getOverlapRanges(int left, int right) {43 44 IT l = ranges.upper_bound(left);45 46 IT r = ranges.upper_bound(right);47 if (l != ranges.begin() && (--l)->second < left)48 ++l;49 return {l, r};50 }51};52