All problems

Problem 518

Count of Range Sum

Hard · 30 pts · Array, Divide and Conquer, Merge Sort, Prefix Sum

Problem

Count the non-empty blocks of consecutive elements whose sum lies between lower and upper inclusive. Blocks at different positions count separately. With prefix sums P, a block from i to j - 1 qualifies when lower <= P[j] - P[i] <= upper. Count those pairs i < j with a merge sort over the prefix sums: before merging two sorted halves, two moving pointers count, for each left value, how many right values fall into its window.

Input

The first line contains N, lower and upper. The second line contains N integers.

Output

Print the number of subarrays whose sum is in [lower, upper].

Constraints

1 <= N <= 100000; -2^31 <= A[i] <= 2^31 - 1; -100000 <= lower <= upper <= 100000

Example input

3 -2 2
-2 5 -1

Example output

3

Explanation

In -2 5 -1 with lower = -2 and upper = 2, the blocks [-2], [-1] and [-2 5 -1] have sums -2, -1 and 2, all within the range. The other blocks sum to 5, 3 and 4, so the answer is 3.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Sum of Subarray Ranges Next: Reverse Pairs