- 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
- 71 lines of C++ from the credited upstream file 3161.cpp.
- The implementation visibly relies on sequence storage, ordered lookup.
- 5 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 FenwickTree {2 public:3 FenwickTree(int n) : vals(n + 1) {}4 5 void maximize(int i, int val) {6 while (i < vals.size()) {7 vals[i] = max(vals[i], val);8 i += lowbit(i);9 }10 }11 12 int get(int i) const {13 int res = 0;14 while (i > 0) {15 res = max(res, vals[i]);16 i -= lowbit(i);17 }18 return res;19 }20 21 private:22 vector<int> vals;23 24 static int lowbit(int i) {25 return i & -i;26 }27};28 29class Solution {30 public:31 vector<bool> getResults(vector<vector<int>>& queries) {32 const int n = min(50000, static_cast<int>(queries.size()) * 3);33 vector<bool> ans;34 FenwickTree tree(n + 1);35 set<int> obstacles{0, n}; 36 37 for (const vector<int>& query : queries) {38 const int type = query[0];39 if (type == 1) {40 const int x = query[1];41 obstacles.insert(x);42 }43 }44 45 for (auto it = obstacles.begin(); std::next(it) != obstacles.end(); ++it) {46 const int x1 = *it;47 const int x2 = *std::next(it);48 tree.maximize(x2, x2 - x1);49 }50 51 for (int i = queries.size() - 1; i >= 0; --i) {52 const int type = queries[i][0];53 const int x = queries[i][1];54 if (type == 1) {55 const auto it = obstacles.find(x);56 if (next(it) != obstacles.end()) 57 tree.maximize(*next(it), *next(it) - *prev(it));58 obstacles.erase(it);59 } else {60 const int sz = queries[i][2];61 const auto it = obstacles.upper_bound(x);62 const int prev = *std::prev(it);63 ans.push_back(tree.get(prev) >= sz || x - prev >= sz);64 }65 }66 67 ranges::reverse(ans);68 return ans;69 }70};71