- Choose the aggregate stored for each interval or prefix.
- Build or initialize the structure from the input.
- Apply updates and combine the affected nodes to answer each query.
Code notes
- 54 lines of C++ from the credited upstream file count-smaller-elements-with-opposite-parity.cpp.
- The implementation visibly relies on sequence storage, hash lookup.
- 4 loop blocks detected.
Complexity
Count the build once, then multiply the logarithmic update or query path by the number of operations.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class BIT {6public:7 BIT(int n) : bit_(n + 1) { 8 }9 10 void add(int i, int val) {11 ++i;12 for (; i < size(bit_); i += lower_bit(i)) {13 bit_[i] += val;14 }15 }16 17 int query(int i) const {18 ++i;19 int total = 0;20 for (; i > 0; i -= lower_bit(i)) {21 total += bit_[i];22 }23 return total;24 }25 26private:27 inline int lower_bit(int i) const {28 return i & -i;29 }30 31 vector<int> bit_;32};33 34class Solution {35public:36 vector<int> countSmallerOppositeParity(vector<int>& nums) {37 vector<int> sorted_nums(nums);38 ranges::sort(sorted_nums);39 sorted_nums.erase(unique(begin(sorted_nums), end(sorted_nums)), end(sorted_nums));40 unordered_map<int, int> val_to_idx;41 for (int i = 0; i < size(sorted_nums); ++i) {42 val_to_idx[sorted_nums[i]] = i;43 }44 vector<BIT> bit(2, BIT(size(val_to_idx)));45 vector<int> result(size(nums));46 for (int i = size(nums) - 1; i >= 0; --i) {47 const auto& idx = val_to_idx[nums[i]];48 result[i] = bit[1 ^ (nums[i] % 2)].query(idx - 1);49 bit[nums[i] % 2].add(idx, 1);50 }51 return result;52 }53};54