Problem: time limit per test: 1.5 seconds memory limit per test: 256 megabytes input: standard input output: standard output
Given 2 numbers N and Q, an array A of N number and Q number of pairs L, R. For each query Q print a single line that contains the summation of all numbers from index L to index R.
Input
- First line contains two numbers N, Q (1≤N,Q≤10^5) where N is number of elements in A and Q is number of query pairs.
- Second line contains N numbers**(1 ≤ Ai ≤ 10^9)**.
- Next Q lines contains L,R (1 ≤ L ≤ R ≤ N).
Output For each query Q print a single line that contains the summation of all numbers from index L to index R.
Examples:
input
6 3
6 4 2 7 2 7
1 3
3 6
1 6
output
12
18
28
input
4 3
5 5 2 3
1 3
2 3
1 4
output
12
7
15
My Code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, q;
scanf("%d %d", &n, &q);
long long int sum[100001];
for (int i = 0; i < n; i++)
{
long long int num;
scanf("%lld", &num);
if (i == 0)
{
sum[i] = num;
}
else
{
sum[i] = sum[i-1] + num;
}
}
for (int j = 0; j < q; j++)
{
int l,r;
scanf("%d %d", &l, &r);
if (l == 1)
{
printf("%d\n", sum[r - 1]);
}
else
{
printf("%d\n", sum[r - 1] - sum[l - 2]);
}
}
return 0;
}
I tried to solve by defining an array named sum. The first loop will scan individually and will store in the sum array by adding with the previous input. Then, in the 2nd loop it will scan the range and will print the summation. If l equals 1 then the summation is at index [r-1] in the sum array. Else, the summation at index [l-2] will be subtracted from the summation at index [r-1].
Explaining my algorithm:
input:
6 1
6 4 2 7 2 7
3 6
Explanation:
sum[0] = 6, sum[1] = 10, sum[2] = 12, sum[3] = 19, sum[4] = 21, sum[5] = 28
Answer will be ( sum[6 - 1] - sum[3 - 2] )
= ( sum[5] - sum[1] )
= 28 - 10
= 18
= 2+7+2+7
This approach has successfully passed three tests. But, it shows "Wrong answer on test 4". Please help me find my mistake.
printf("%d\n", sum[r - 1])
should be printf("%lld\n", sum[r - 1])
. Ditto for printing sum[r - 1] - sum[l - 2]
.
The code could be shortened by storing 0 in sum[0]
:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, q;
scanf("%d%d", &n, &q);
long long int sum[100001];
sum[0] = 0;
for (int i = 1; i <= n; i++)
{
long long int num;
scanf("%lld", &num);
sum[i] = sum[i - 1] + num;
}
for (int j = 0; j < q; j++)
{
int l,r;
scanf("%d%d", &l, &r);
printf("%lld\n", sum[r] - sum[l - 1]);
}
return 0;
}