Answered step by step
Verified Expert Solution
Question
1 Approved Answer
Please use binary search to fill in the missing part of the code. The previous answers were not correct. Thank you! Time limit: 5000ms Memory
Please use binary search to fill in the missing part of the code. The previous answers were not correct. Thank you! 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------------------------- #include#include #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 boundary } // 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 ", 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
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started