CSES - Range Update Queries
Authors: Benjamin Qi, Óscar Garries, Nathan Gong
Explanation
Implementation Note
We will be using 1-based arrays (index starting from 1) throughout this problem. The element at index 0 will always be 0.
We can solve this problem by taking advantage of a difference array, where for all . To calculate using , we can find the sum of all the values in up to the -th index:
This means that we can answer point queries in time by calculating prefix sums of with a segment tree or binary-indexed tree.
To respond to range updates on an interval , we can increment by and decrement by . This way, when answering point queries, all the values at indices will be increased by and all values at indices less than or greater than remain unchanged.
Implementation
Time Complexity:
C++
#include <bits/stdc++.h>using namespace std;using ll = long long;using ld = long double;template <class T> struct Seg {int n;T ID = 0;vector<T> seg;
Java
import java.io.*;import java.util.*;public class RangeUpdateQueries {public static void main(String[] args) {Kattio io = new Kattio();int n = io.nextInt();int q = io.nextInt();int[] arr = new int[n + 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!