This page is still under construction.

Parts of this page are still being built. What you see may change.

G-Avoiding Sequence

Time limit1sMemory limit128 MB

Summary
Count permutations of a set where consecutive elements never differ by a multiple of G, modulo a prime.
Level

Medium7 of 10

Topics
Dynamic programming, Combinatorics, Math
Solved
No attempts yet

Problem

You are given a set SS of distinct integers and an integer GG. A sequence of integers is called a G-Avoiding Sequence if both of the following conditions hold:

  1. the sequence is a permutation of the elements of SS; and
  2. for any two consecutive elements AA and BB in the sequence, A−BA - B is not divisible by GG.

Compute the number of G-Avoiding Sequences modulo the prime 1,234,567,891.

Input

The input consists of several test cases. The first line of each test case contains two integers NN (1≤N≤2001 \le N \le 200), the size of SS, and GG (1≤G≤10001 \le G \le 1000). The next line contains NN integers, the elements of SS, each between 00 and 10610^6.

The input ends with a single line containing N=G=0N = G = 0, which must not be processed.

Output

For each test case, output a single line containing the number of G-Avoiding Sequences modulo 1,234,567,891.

Examples3

  1. Example 1

    Input
    4 3
    1 2 3 4
    3 100
    10 110 42
    0 0
    
    Expected output
    12
    2
    
  2. Example 2

    Input
    1 5
    7
    0 0
    
    Expected output
    1
    
  3. Example 3

    Input
    2 3
    1 2
    0 0
    
    Expected output
    2