#P6006. [USACO20JAN] Farmer John Solves 3SUM G

[USACO20JAN] Farmer John Solves 3SUM G

Description

Farmer John believes he has made a major breakthrough in algorithm design: he claims to have found a near-linear-time algorithm for the 3SUM problem, a famous algorithmic problem for which no solution significantly faster than quadratic time has been found so far. One version of the 3SUM problem is: given an integer array s1,,sms_1,\ldots,s_m, compute the number of unordered triples of distinct indices i,j,ki,j,k such that si+sj+sk=0s_i+s_j+s_k=0 (ii, jj, and kk are all different).

To test Farmer John’s claim, Bessie provides an array AA of NN integers (1N50001 \leq N \leq 5000). Bessie will also ask QQ queries (1Q1051 \leq Q \leq 10^5), where each query consists of two indices 1aibiN1 \leq a_i \leq b_i \leq N. For each query, Farmer John must solve the 3SUM problem on the subarray A[aibi]A[a_i \ldots b_i].

Unfortunately, Farmer John has just discovered a bug in his algorithm. He is confident he can fix it, but in the meantime, he asks you to help him pass Bessie’s tests first.

Input Format

The first line contains two space-separated integers NN and QQ.

The second line contains the elements of AA, namely A1,,ANA_1,\ldots,A_N, separated by spaces.

Each of the next QQ lines contains two space-separated integers aia_i and bib_i, describing a query.

It is guaranteed that for each array element AiA_i, we have 106Ai106-10^6 \leq A_i \leq 10^6.

Output Format

Output QQ lines. The ii-th line contains one integer, the answer to the ii-th query. Note that you need to use a 64-bit integer type to avoid overflow.

7 3
2 0 -1 1 -2 3 3
1 5
2 4
1 7
2
1
4

Hint

Sample Explanation

For the first query, all valid triples are (A1,A2,A5)(A_1,A_2,A_5) and (A2,A3,A4)(A_2,A_3,A_4).

Subtasks

  • Test cases 242 \sim 4 satisfy N500N \leq 500.
  • Test cases 575 \sim 7 satisfy N2000N \leq 2000.
  • Test cases 8158 \sim 15 have no additional constraints.

Translated by ChatGPT 5