Count pairs

2.9

17 votes
Sorting, Hashmap, Implementation, Hash Tables, Data Structures, Basics of Hash Tables, Hashing, Math, Observation
Problem

You are given an array A consisting of N non-negative integers. You are also given 2 integers p(a prime number) and k. You are required to count number of pairs (i,j) where, 1i<jN and satisying: 

                                                     (A2i+A2j+AiAj) mod p=k 

where a mod p=b means that b is the remainder when a is divided by p. In particular, 0b<p.

You are given T test cases.

Input format

  • The first line contains a single integer T denoting the number of test cases.
  • For each test case:
    • The first line contains three space-separated integers N, k, and p denoting the length of the array, the required remainder/modulo, and the prime number respectively.
    • The second line contains N space-separated integers denoting the integer array A.

Output format

For each test case, print the number of pairs satisfying the equation in a separate line.

Constraints

1T10001N5×1051p109p is prime0k<p0Ai109Sum of N over all test cases does not exceed 106

Time Limit: 1.5
Memory Limit: 256
Source Limit:
Explanation

In the first sample, N=4,k=1,p=2,A=[3,2,1,0]. Caculations for each pair (i,j)  are shown below:

  • (1,2) : A21+A22+A1A2 mod p=(9+4+6) mod 2=1.
  • (1,3) : A21+A23+A1A3 mod p=(9+1+3) mod 2=1.
  • (1,4) : A21+A24+A1A4 mod p=(9+0+0) mod 2=1.
  • (2,3) : A22+A23+A2A3 mod p=(4+1+4) mod 2=1.
  • (2,4) : A22+A24+A2A4 mod p=(4+0+0) mod 2=0.
  • (3,4) : A23+A24+A3A4 mod p=(1+0+0) mod 2=1.
  • Therefore, the number of pairs satisfying the equation are 5.

In the second sample, N=8,k=0,p=3,A=[9,2,1,8,4,5,9,10]. Valid pairs (i,j) are: (1,7),(2,4),(2,6),(3,5),(3,8),(4,6),(5,8).

Editor Image

?