CSES - Increasing Array Queries
Author: Andi Qu
Appears In
Time Complexity: .
In this problem, we can answer the queries offline (i.e. read in the queries and process them in a different order). More specifically, we process queries in order of their left endpoints.
First, let's think about how we'd answer a single query . Consider the following algorithm:
- Let and .
- For each in :
- If , then set and increment .
- Otherwise, add to the answer.
Notice how each (except the last) contributes a fixed amount to the answer, regardless of . If is the prefix sum array of and is the index of in , then this amount is
This means that for a fixed , we can compute each and their contributions, and then use std::upper_bound
and a BIT to answer queries with variable !
If we want to change , notice how we can update efficiently by using a monotone stack. Since each 's contribution depends on after it, the contributions of the old don't change.
Again, we use std::upper_bound
and a BIT to answer queries.
C++
#include <bits/stdc++.h>typedef long long ll;using namespace std;const ll INF = 1e18;int n, q;ll x[200002], pref[200002], ans[200002];ll contrib[200002], bit[200002];vector<pair<int, int>> bckt[200001];
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!