Farmer John Solves 3SUM
Farmer John Solves 3SUM
Farmer John believes he has made a major breakthrough in algorithm design: he claims to have found a nearly linear time algorithm for the 3SUM problem, an algorithmic problem famous for the fact that no known solution exists running in substantially better than quadratic time. One formulation of the 3SUM problem is the following: given an array s1
, ..., sm
of integers, count the number of unordered triples of distinct indices i, j, k such that si
+ sj
+ sk
= 0.
To test Farmer John's claim, Bessie has provided an array A of n integers. Bessie also asks q queries, each of which consists of two indices 1≤ai≤bi≤N. For each query, Farmer John must solve the 3SUM problem on the subarray A[ai
...bi
].
Unfortunately, Farmer John has just discovered a flaw in his algorithm. He is confident that he can fix the algorithm, but in the meantime, he asks that you help him pass Bessie's test!
Input
The first line contains two integers n (1 ≤ n ≤ 5000) and q (1 ≤ q ≤ 105
). The second line contains the space-separated elements A1
,..., An
of array A. Each of the subsequent q lines contains two space-separated integers ai
and bi
, representing a query.
It is guaranteed that −106
≤ Ai
≤ 106
for every array element Ai
.
Output
The output should consist of q lines, with each line i containing a single integer - the answer to the i-th query. Note that you should use 64-bit integers to avoid overflow.
Example
For the first query, the possible triples are (A1
, A2
, A5
) and (A2
, A3
, A4
).
7 3 2 0 -1 1 -2 3 3 1 5 2 4 1 7
2 1 4