- 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
- 73 lines of C++ from the credited upstream file 2916.cpp.
- The implementation visibly relies on sequence storage, hash lookup.
- 1 loop block 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.
1class LazySegmentTree {2 public:3 LazySegmentTree(int n, int kMod)4 : n(n), kMod(kMod), lazy(4 * n), sums(4 * n), squaredSums(4 * n) {}5 6 void updateRange(int l, int r) {7 return updateRange(0, 0, n - 1, l, r);8 }9 10 void propagate(int i, int l, int r) {11 const int gap = r - l + 1;12 13 14 squaredSums[i] += 2 * lazy[i] * sums[i] + lazy[i] * lazy[i] * gap;15 squaredSums[i] %= kMod;16 sums[i] += lazy[i] * gap;17 sums[i] %= kMod;18 if (l < r) {19 lazy[i * 2 + 1] += lazy[i];20 lazy[i * 2 + 2] += lazy[i];21 }22 lazy[i] = 0;23 }24 25 int getTreeSquaredSums() {26 return squaredSums[0];27 }28 29 private:30 const int kMod;31 const int n;32 vector<long> lazy;33 vector<long> sums;34 vector<long> squaredSums;35 36 void updateRange(int i, int start, int end, int l, int r) {37 if (lazy[i] > 0)38 propagate(i, start, end);39 if (end < l || start > r)40 return;41 if (start >= l && end <= r) {42 lazy[i] = 1;43 propagate(i, start, end);44 return;45 }46 const int mid = (start + end) / 2;47 updateRange(i * 2 + 1, start, mid, l, r);48 updateRange(i * 2 + 2, mid + 1, end, l, r);49 sums[i] = (sums[i * 2 + 1] + sums[i * 2 + 2]) % kMod;50 squaredSums[i] = (squaredSums[i * 2 + 1] + squaredSums[i * 2 + 2]) % kMod;51 }52};53 54class Solution {55 public:56 int sumCounts(vector<int>& nums) {57 constexpr int kMod = 1'000'000'007;58 const int n = nums.size();59 int ans = 0;60 unordered_map<int, int> lastSeen;61 LazySegmentTree tree(n, kMod);62 63 for (int r = 0; r < n; ++r) {64 const int l = lastSeen.contains(nums[r]) ? lastSeen[nums[r]] + 1 : 0;65 tree.updateRange(l, r);66 lastSeen[nums[r]] = r;67 ans = (ans + tree.getTreeSquaredSums()) % kMod;68 }69 70 return ans;71 }72};73