Time Complexity:
Let's maintain an array , which is sorted by height. To answer a query of type C, we can simply binary search on the endpoints of the query.
Now, we just need to support updates. Let's first binary search for the first position such that . Let . We just need to increment the range, by while keeping sorted.
However, we cannot just add to all elements in the range, because this might break the sorted order. This happens iff there is some index inside , such that ; if we increment the range , then , which is an inversion.
To prevent this error, we find another range , such that for all ; this can be found with binary search. Since all sastify , we can increment first. Then, since we need to increment a total of elements, we have elements left. We increment the range by one.
Notice that this doesn't create any inversions because is greater than before the update: after the update, the array would be non-decreasing.
Updates and queries can be handled with a lazy segment tree, but a binary indexed tree would suffice since we only need point queries.
C++
#include <bits/stdc++.h>using namespace std;#define N 100000int n, q, a[N], bit[N];void add(int l, int r, int x) { // add x to [l, r]if (r < l) return;for (; l < n; l |= l + 1) bit[l] += x;
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!