CSES - Range Update Queries

Authors: Benjamin Qi, Óscar Garries, Nathan Gong

Table of Contents

ExplanationImplementation

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 diff[i]=arr[i]arr[i1]\texttt{diff}[i] = \texttt{arr}[i]-\texttt{arr}[i-1] for all ii (1in)(1 \leq i \leq n). To calculate arr[i]\texttt{arr}[i] using diff\texttt{diff}, we can find the sum of all the values in diff\texttt{diff} up to the ii-th index:

arr[i]=j=0idiff[j]=diff[0]+diff[1]++diff[i]\texttt{arr}[i] = \sum^i_{j=0}\texttt{diff}[j] = \texttt{diff}[0] + \texttt{diff}[1] + \dots + \texttt{diff}[i]

This means that we can answer point queries in O(logn)\mathcal{O}(\log n) time by calculating prefix sums of diff\texttt{diff} with a segment tree or binary-indexed tree.

To respond to range updates on an interval [a,b][a, b], we can increment diff[a]\texttt{diff}[a] by uu and decrement diff[b+1]\texttt{diff}[b+1] by uu. This way, when answering point queries, all the values at indices aba \dots b will be increased by uu and all values at indices less than aa or greater than bb remain unchanged.

Implementation

Time Complexity: O(qlogn)\mathcal{O}(q\log n)

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!