#abc367c. C - Enumerate Sequences

C - Enumerate Sequences

Score : 300300 points

问题陈述

以升序的字典序打印所有长度为 NN 的整数序列,满足以下条件:

  • ii 个元素在 11RiR_i(包括 11RiR_i)之间。
  • 所有元素的和是 KK 的倍数。

什么是序列的字典序?如果满足以下条件之一,则序列 A=(A1,,AA)A = (A_1, \ldots, A_{|A|}) 字典序小于 序列 B=(B1,,BB)B = (B_1, \ldots, B_{|B|})

  1. A<B|A|<|B|(A1,,AA)=(B1,,BA)(A_{1},\ldots,A_{|A|}) = (B_1,\ldots,B_{|A|})
  2. 存在一个整数 1imin{A,B}1\leq i\leq \min\{|A|,|B|\} 使得以下两个条件同时成立:
    • (A1,,Ai1)=(B1,,Bi1)(A_{1},\ldots,A_{i-1}) = (B_1,\ldots,B_{i-1})
    • Ai<BiA_i < B_i

以上为大语言模型 kimi 翻译,仅供参考。

Problem Statement

Print all integer sequences of length NN that satisfy the following conditions, in ascending lexicographical order.

  • The ii-th element is between 11 and RiR_i, inclusive.
  • The sum of all elements is a multiple of KK.

What is lexicographical order for sequences? A sequence A=(A1,,AA)A = (A_1, \ldots, A_{|A|}) is lexicographically smaller than B=(B1,,BB)B = (B_1, \ldots, B_{|B|}) if either 1. or 2. below holds:

  1. A<B|A|<|B| and (A1,,AA)=(B1,,BA)(A_{1},\ldots,A_{|A|}) = (B_1,\ldots,B_{|A|}).
  2. There exists an integer 1imin{A,B}1\leq i\leq \min\{|A|,|B|\} such that both of the following are true:
    • (A1,,Ai1)=(B1,,Bi1)(A_{1},\ldots,A_{i-1}) = (B_1,\ldots,B_{i-1})
    • Ai<BiA_i < B_i

Constraints

  • All input values are integers.
  • 1N81 \le N \le 8
  • 2K102 \le K \le 10
  • 1Ri51 \le R_i \le 5

Input

The input is given from Standard Input in the following format:

NN KK

R1R_1 R2R_2 \dots RNR_N

Output

Print the answer in the following format, where XX is the number of sequences to print, the ii-th of which is Ai=(Ai,1,Ai,2,,Ai,N)A_i=(A_{i,1},A_{i,2},\dots,A_{i,N}):

A1,1A_{1,1} A1,2A_{1,2} \dots A1,NA_{1,N}

A2,1A_{2,1} A2,2A_{2,2} \dots A2,NA_{2,N}

\vdots

AX,1A_{X,1} AX,2A_{X,2} \dots AX,NA_{X,N}

Sample Input 1

3 2
2 1 3

Sample Output 1

1 1 2
2 1 1
2 1 3

There are three sequences to be printed, which are (1,1,2),(2,1,1),(2,1,3)(1,1,2),(2,1,1),(2,1,3) in lexicographical order.

Sample Input 2

1 2
1

Sample Output 2

There may be no sequences to print.
In this case, the output can be empty.

Sample Input 3

5 5
2 3 2 3 2

Sample Output 3

1 1 1 1 1
1 2 2 3 2
1 3 1 3 2
1 3 2 2 2
1 3 2 3 1
2 1 2 3 2
2 2 1 3 2
2 2 2 2 2
2 2 2 3 1
2 3 1 2 2
2 3 1 3 1
2 3 2 1 2
2 3 2 2 1