- 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
- 89 lines of C++ from the credited upstream file number-of-integers-with-popcount-depth-equal-to-k-ii.cpp.
- The implementation visibly relies on sequence storage.
- 6 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.
1234 56class BIT {7public:8 BIT(int n) : bit_(n + 1) { 9 }10 11 void add(int i, int val) {12 ++i;13 for (; i < size(bit_); i += lower_bit(i)) {14 bit_[i] += val;15 }16 }17 18 int query(int i) const {19 ++i;20 int total = 0;21 for (; i > 0; i -= lower_bit(i)) {22 total += bit_[i];23 }24 return total;25 }26 27private:28 int lower_bit(int i) const {29 return i & -i;30 }31 32 vector<int> bit_;33};34 35int bit_length(int64_t x) {36 return (x ? std::__lg(x) : -1) + 1;37}38 39int ceil_log2(int64_t x) {40 return std::__lg(x - 1) + 1;41};42 43pair<vector<int>, int> init() {44 int64_t MAX_N = 1e15;45 static const int MAX_BIT_LEN = bit_length(MAX_N);46 vector<int> D(MAX_BIT_LEN + 1, 0);47 for (int i = 2; i < size(D); ++i) {48 D[i] = D[__builtin_popcount(i)] + 1;49 }50 int MAX_K = 0;51 for (; MAX_N != 1; ++MAX_K) { 52 MAX_N = ceil_log2(MAX_N);53 }54 return {D, MAX_K};55}56 57const auto& [D, MAX_K] = init();58class Solution {59public:60 vector<int> popcountDepth(vector<long long>& nums, vector<vector<long long>>& queries) {61 const auto& count = [](int64_t x) {62 return x != 1 ? D[__builtin_popcountll(x)] + 1 : 0;63 };64 65 vector<BIT> bit(MAX_K + 1, BIT(size(nums)));66 for (int i = 0; i < size(nums); ++i) {67 bit[count(nums[i])].add(i, +1);68 }69 vector<int> result;70 for (const auto& q : queries) {71 if (q[0] == 1) {72 const int l = q[1], r = q[2], k = q[3];73 assert(k < size(bit));74 result.emplace_back(bit[k].query(r) - bit[k].query(l - 1));75 } else {76 const auto& i = q[1], &x = q[2];77 const auto& old_d = count(nums[i]);78 const auto& new_d = count(x);79 if (new_d != old_d) {80 bit[old_d].add(i, -1);81 bit[new_d].add(i, +1);82 }83 nums[i] = x;84 }85 }86 return result;87 }88};89