prefix and
Enter a sequence of integers of length n. Next, enter m queries, and enter a pair of l, r for each query. For each query, output the sum from the lth number to the rth number in the original sequence.
input format
The first line contains two integers n and m.
The second line contains n integers, representing a sequence of integers.
Next m lines, each line contains two integers l and r, representing a query range.
output format
A total of m lines, each line outputs a query result.
data range
1≤l≤r≤n
1≤n,m≤100000
−1000≤The value of the element in the array≤1000
Input sample:
5 3
2 1 3 6 4
1 2
1 3
twenty four
Sample output:
3
6
10
Solution
This code implements a prefix sum algorithm to calculate the prefix sum of an array q
. The prefix sum of an array is the sum of all elements up to a certain index. For example, the prefix sum of the first i
elements of an array q
is s[i] = q[1] + q[2] + ... + q[i]
.
The code first reads two integers n
and m
from standard input, which represent the length of the array q
and the number of queries to perform, respectively. It then reads the elements of the array q
from standard input using a loop, and calculates the prefix sum s
of the array q
. Specifically, it uses another loop to iterate over the elements of q
, and calculates the prefix sum s
by storing the sum of the current element and the previous prefix sum in s[i] = s[i - 1] + q[i]
.
After calculating the prefix sum, the code enters a loop to perform the queries. In each iteration of the loop, it reads two integers l
and r
from standard input, which represent the left and right indices of the subarray to query. It then calculates the sum of the subarray by subtracting the prefix sum at index l - 1
from the prefix sum at index r
, and outputs the result to standard output.
Note that this code assumes that the array q
is 1-indexed. If the array is 0-indexed, the loop that calculates the prefix sum should start at index 0 instead of 1.
#include <bits/stdc++.h>
using namespace std;
const int N = 10010;
int n, m;
int q[N], s[N];
int main() {
cin >> n >> m;
for (int i = 1; i <= n; i ++ ) cin >> q[i];
for (int i = 1; i <= n; i ++ ) s[i] = s[i - 1] + q[i];
while (m -- ) {
int l, r;
cin >> l >> r;
cout << s[r] - s[l - 1] << endl;
}
return 0;
}