classBIT { public: int* c; int n; public: BIT(int _n) { n = _n; c = newint[n + 1]; for (int i = 0; i <= n; i++) c[i] = 0; } staticconstexprintlowbit(int x){ return x & (-x); } voidadd(int x){ while (x <= n) { c[x]++; x += lowbit(x); } } intquery(int x){ int sum = 0; while (x) { sum += c[x]; x -= lowbit(x); } return sum; } };
classSolution { public: intcountRangeSum(vector<int>& a, int lower, int upper){ set<longlong> s; int m = a.size(); longlong *sum = newlonglong[m + 1]; sum[0] = 0; for (int i = 0; i <= m; i++) { if (i) sum[i] = sum[i - 1] + a[i - 1]; s.insert(sum[i]); s.insert(sum[i] - upper); s.insert(sum[i] - lower); } unordered_map<longlong, int> mp; int n = s.size(), idx = 0; BIT bit(n); for (auto x : s) mp[x] = ++idx; int res = 0; for (int i = 0; i <= m; i++) { int l = mp[sum[i] - upper], r = mp[sum[i] - lower]; res += bit.query(r) - bit.query(l - 1); bit.add(mp[sum[i]]); } return res; } };