CSES - Prefix Sum Queries
Author: Dong Liu
Appears In
Time Complexity:
Solution
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
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 .
Code
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); } LSegTree() {}LSegTree(int N) : N(N), t(4*(N+1),U), lz(4*(N+1),0) {}void pull(int i) { t[i] = F(t[i*2],t[i*2+1]); }
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!