Farmer John Solves 3SUM

여러 부분 배열 질의마다 세 값의 합이 0이 되는 서로 다른 세 인덱스 조합의 개수를 센다.

어려움8동적 계획법누적 합해시맵완전 탐색아직 제출이 없습니다시간 제한2초메모리 제한512 MB

문제

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 s_1,,s_ms\_1,\dots,s\_m of integers, count the number of unordered triples of distinct indices i,j,ki,j,k such that s_i+s_j+s_k=0s\_i + s\_j + s\_k = 0.

To test Farmer John's claim, Bessie has provided an array AA of NN integers (1N50001 \leq N \leq 5000). Bessie also asks QQ queries (1Q1051 \leq Q \leq 10^5), each of which consists of two indices 1a_ib_iN1 \leq a\_i \leq b\_i \leq N. For each query, Farmer John must solve the 3SUM problem on the subarray A\[a_ib_i]A\[a\_i \dots b\_i].

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!

입력

The first line contains two space-separated integers NN and QQ. The second line contains the space-separated elements A_1,,A_NA\_1,\dots,A\_N of array AA. Each of the subsequent QQ lines contains two space-separated integers a_ia\_i and b_ib\_i, representing a query.

It is guaranteed that 106A_i106-10^6 \leq A\_i \leq 10^6 for every array element A_iA\_i.

출력

The output should consist of QQ lines, with each line ii containing a single integer---the answer to the ii-th query. Note that you should use 64-bit integers to avoid overflow.

힌트

For the first query, the possible triples are (A_1,A_2,A_5)(A\_1,A\_2,A\_5) and (A_2,A_3,A_4).(A\_2,A\_3,A\_4).