THINK FIRST·CODE LATER

← All labs

Range sums with prefix sums

Problem

You are given an array of n integers and q queries. Each query l r (0-based, 0 ≤ l ≤ r < n) asks for a[l] + a[l+1] + … + a[r].

Answer every query, and compare two strategies by counting operations (never measure time):

  • Naive: add up the elements of each range directly. Count one addition per element added, i.e. r - l + 1 per query.
  • Prefix sums: first build prefix[0..n] with prefix[0] = 0 and prefix[i+1] = prefix[i] + a[i] (count n operations), then answer each query as prefix[r+1] - prefix[l] (count 1 operation per query).

Input: n, then n integers, then q, then q lines l r. Print one line per query, then the two counts, exactly as below. Sums can exceed the int range — use long.

For the input

5
3 -1 4 1 5
3
0 4
1 3
2 2

the output is

sum(0..4) = 12
sum(1..3) = 4
sum(2..2) = 4
Naive additions: 9
Prefix-sum operations: 8

Both strategies must give the same sums; print the prefix-sum answer.

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

d6-2-data-1.txt

5
3 -1 4 1 5
3
0 4
1 3
2 2
What your program must print for d6-2-data-1.txt
sum(0..4) = 12
sum(1..3) = 4
sum(2..2) = 4
Naive additions: 9
Prefix-sum operations: 8

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < d6-2-data-1.txt

Windows PowerShell does not understand <:

Get-Content d6-2-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.