Range Sum Query
Time limit: 5000ms
Memory limit: 256mb
Description:
Given a sorted array A of positive integers (in ascending order), please perform Q queries: what is the sum of elements in range [a, b]?
Hint: a linear scan may exceed the time limit in some testcases. Please use the binary search.
-------------------------Copy the following code, complete it and submit-------------------------
/*
I, <Your Full Name>, am submitting the assignment for
an individual project.
I declare that the assignment here submitted is original except for
source material explicitly acknowledged, the piece of work, or a part
of the piece of work has not been submitted for more than one purpose
(i.e. to satisfy the requirements in two different courses) without
declaration. I also acknowledge that I am aware of University policy
and regulations on honesty in academic work, and of the disciplinary
guidelines and procedures applicable to breaches of such policy and
regulations, as contained in the University website
http://www.cuhk.edu.hk/policy/academichonesty/.
It is also understood that assignments without a properly signed
declaration by the student concerned will be graded as zero by the
teacher(s).
*/
#include <stdio.h>
#include <stdlib.h>
#define MAX_LEN 1024 * 1024 * 10
#define MAX_QUERIES 1024 * 100
int range_sum_query(int a[], int n, int l, int r) {
// WRITE YOUR CODE HERE
// HINT: use binary search to find the boundry
}
// DO NOT MODIFY THE CODE BELOW
int main() {
int n, q;
int left[MAX_QUERIES];
int right[MAX_QUERIES];
int result;
int i;
int *a;
a = (int *)malloc(MAX_LEN * sizeof(int));
scanf("%d", &n);
scanf("%d", &q);
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
for (i = 0; i < q; i++) {
scanf("%d %d", &left[i], &right[i]);
}
for (i = 0; i < q; i++) {
result = range_sum_query(a, n, left[i], right[i]);
printf("%d\n", result);
}
free(a);
return 0;
}
-----------------------------------------End of Code-----------------------------------------
Input:
First line is two integers N and Q;
Second line is the array of N positive integers which has been sorted in ascending order;
Then Q lines follows: each line uses two integers a and b to represent a range [a, b].
0 <= N <= 10^7, 0 <= Q <= 10^5
Output:
The output has Q lines. The i-th line is the answer of the i-th range sum query.
If there is no elements in the input range, please return 0.
Sample Input 1:
4 3
1 3 5 8
4 6
2 3
6 7
Sample Output 1:
5
3
0
Submit