CF BUDDY
← Problems·

1857F · Sum and Product

1600 · binary search, data structures, math

Problem: You have an array aa of length nn.

Your task is to answer qq queries: given x,yx,y, find the number of pairs ii and jj (1i<jn1 \le i < j \le n) that both ai+aj=xa_i + a_j = x and aiaj=ya_i \cdot a_j = y.

That is, for the array [1,3,2][1,3,2] and asking for x=3,y=2x=3,y=2 the answer is 11:

  • i=1i=1 and j=2j=2 fail because 1+3=41 + 3 = 4 and not 3,3, also 13=31 \cdot 3=3 and not 22;
  • i=1i=1 and j=3j=3 satisfies both conditions;
  • i=2i=2 and j=3j=3 fail because 3+2=53 + 2 = 5 and not 3,3, also 32=63 \cdot 2=6 and not 22;

Input Format: The first line contains one integer tt (1t1041\le t\le 10^4) — the number of test cases.

The second line of each test case contains one integer nn (1n21051 \le n \le 2\cdot 10^5) — the length of the array aa.

The third line of each test case contains nn integers a1,a2,,ana_1,a_2,\dots,a_n (1ai1091 \le |a_i| \le 10^9) — array aa.

The fourth line of each test case contains the integer qq (1q21051 \le q \le 2\cdot 10^5) — the number of requests.

The next qq lines contain two numbers each xx and yy (1x2109,1y10181 \le |x|\le 2\cdot 10^9,1\le |y|\le 10^{18}) — request.

It is guaranteed that the sum of nn over all test cases does not exceed 21052\cdot 10^5. This is also guaranteed for the sum of qq values.

Output Format: For each test case print a line with qq numbers — the answers to the queries.

Note: For the first test case, let's analyze each pair of numbers separately:

  • pair (a1,a2)(a_1,a_2): a1+a2=4a_1 + a_2 = 4, a1a2=3a_1 \cdot a_2 = 3
  • pair (a1,a3)(a_1,a_3): a1+a3=3a_1 + a_3 = 3, a1a3=2a_1 \cdot a_3 = 2
  • pair (a2,a3)(a_2,a_3): a2+a3=5a_2 + a_3 = 5, a2a3=6a_2 \cdot a_3 = 6

In the second test case, all combinations of pairs are suitable.

Sample Cases

Case 1

Input

3
3
1 3 2
4
3 2
5 6
3 1
5 5
4
1 1 1 1
1
2 1
6
1 4 -2 3 3 3
3
2 -8
-1 -2
7 12

Output

1 1 0 0 
6 
1 1 3

Similar problems

00:00:00
Loading editor…
Welcome! I'm your coding tutor for this problem. Use the chips below to reveal stored hints or get AI feedback on your code. I'll guide you step by step — never giving away the solution.

Sign in to unlock AI tutor feedback