P2328 [SCOI2005] Super Gray Code

Description

The well-known Gray code refers to a permutation of $2^n$ distinct $n$-bit binary numbers (i.e., $0 \sim 2^n - 1$, with leading zeros added if necessary to ensure $n$ bits). This permutation satisfies the condition that any two adjacent binary numbers differ by at most one bit (e.g., $003$ and $001$ differ by one bit, while $003$ and $030$ differ by two bits, which does not meet the requirement). For instance, when $n=2$, the sequence ($00$, $01$, $11$, $10$) is a valid Gray code. The so-called super Gray code refers to the arrangement of $B$ distinct $n$-digit $B$-ary numbers that satisfies the above conditions. Given $n$ and $B$, find a Gray code that meets the conditions. For numbers greater than $9$, use $A\sim Z$ to represent them ($10\sim 35$).

Input Format

Only one line, containing two integers $n$ and $B$.

Output Format

A total of $B^n$ lines, each line is a base-$B$ number, representing the ordering that meets the required conditions.

Explanation/Hint

$2\leq B\leq 36,1\leq B^n\leq 65535$。 Thanks to @Night_Aurora for the SPJ. Translated by ChatGPT 5