CSES - Prefix Sum Queries
Author: Dong Liu
Time Complexity:
In this problem, we're given an array and we're asked to answer 2 types of queries
- update the value at position to
- calculate the maximum prefix sum in the range
Solution 1 - Segment Tree
In each segment tree node, we will store
- : the sum of the elements in the range
- : the maximum prefix sum in the range
To calculate ,
- The would be equal to .
- The maximum prefix has to end at either the left segment (), or at the right segment (), so would equal .
Now we can build and update any value in our segment tree.
To answer an query, we can split the range into segments. To calculate the answer, we just repeatedly merge these segments until there is one left and take the .
C++
#include <bits/stdc++.h>using namespace std;const int N = 200010;const int S = 1 << 18;int n, q, a[N];struct node {long long sum, pref;
Solution 2 - With Lazy Propagation
We can use a segment tree with lazy propagation to solve this problem. Let be the sum of . We can maintain a segment tree consisting of the maximum in the range of .
To update the value at position to , we add to each of the values in the range .
To answer a query of type 2, our answer would be .
C++
#include <bits/stdc++.h>using namespace std;using ll = long long;template <class T> struct LSegTree {int N;vector<T> t, lz;T U = -1e18;T F(T i, T j) { return max(i, j); }
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!