This repository has been archived on 2022-06-22. You can view files and clone it, but cannot push or open issues or pull requests.
usaco-guide/content/4_Silver/6_Silver_Psum.md
2020-06-08 16:42:55 -04:00

2.3 KiB

slug title author order
/silver/prefix-sums Prefix Sums Eric Wei (incomplete) 6

Given an array of size N, answer Q queries of the following form: Find the sum of all elements between indices i and j.

Standard

Tutorials

This technique is also known as cumulative sum or partial sums.

  • Intro to USACO 11
  • CPH 9.1

Extensions

2D Prefix Sums

Given a 2-dimensional array of size NxM, answer Q queries of the following form: Find the sum of all elements within the rectangle of indices (x1,y1) to (x2,y2).

Difference Array

Task: Given an array of size N, do the following operation Q times: add X to the values between i and j. Afterwards, print the final array.

Solution: Consider the array formed by a_i-a_{i-1}. When processing a range addition, only two values in this difference array change! At the end, we can recover the original array using prefix sums. (The math is left as an exercise to the reader.)

  • (find 1d difference array problem)

Prefix Minimum, XOR, etc.

Similar to prefix sums, you can also take prefix minimum or maximum; but you cannot answer min queries over an arbitrary range with prefix minimum. (This is because minimum doesn't have an inverse operation, like subtraction is to addition.) On the other hand, XOR is its own inverse operation...

More Complex Applications

Instead of storing just the values themselves, you can also take a prefix sum over i\cdot a_i, or 10^i \cdot a_i, for instance.

  • (find iota ps problem)
  • AtCoder Multiple of 2019 (You may want to solve the below problem "Subsequences Summing to Seven" before doing this one.)

Additional Problems