#P5657. [CSP-S 2019] 格雷码
[CSP-S 2019] 格雷码
Problem Description
Usually, people are used to arranging all -bit binary strings in lexicographical order. For example, all 2-bit binary strings in increasing lexicographical order are: 00, 01, 10, 11.
Gray Code is a special way to arrange -bit binary strings. It requires that any two adjacent binary strings differ in exactly one bit. In particular, the first string and the last string are also considered adjacent.
An example of arranging all 2-bit binary strings in Gray Code order is: 00, 01, 11, 10.
There is more than one -bit Gray Code. Below is one algorithm to generate a Gray Code:
- The 1-bit Gray Code consists of two 1-bit binary strings, in the order: 0, 1.
- The first binary strings of the -bit Gray Code can be formed by taking the -bit Gray Code generated by this algorithm (a total of -bit binary strings) in order, and adding a prefix 0 to each string.
- The last binary strings of the -bit Gray Code can be formed by taking the -bit Gray Code generated by this algorithm (a total of -bit binary strings) in reverse order, and adding a prefix 1 to each string.
In summary, the -bit Gray Code consists of the strings of the -bit Gray Code in order with prefix 0, and the strings of the -bit Gray Code in reverse order with prefix 1, making a total of binary strings. Also, for the binary strings in the -bit Gray Code, we number them as according to the order produced by the above algorithm.
With this algorithm, the 2-bit Gray Code can be derived as follows:
- The 1-bit Gray Code is 0, 1.
- The first two Gray codes are 00, 01. The last two Gray codes are 11, 10. Merging them gives 00, 01, 11, 10, numbered from 0 to 3 in order.
Similarly, the 3-bit Gray Code can be derived as follows:
- The 2-bit Gray Code is: 00, 01, 11, 10.
- The first four Gray codes are: 000, 001, 011, 010. The last four Gray codes are: 110, 111, 101, 100. Merging them gives: 000, 001, 011, 010, 110, 111, 101, 100, numbered from 0 to 7 in order.
Now you are given and . Please find the -th binary string in the -bit Gray Code generated by the above algorithm.
Input Format
A single line with two integers and , as described in the statement.
Output Format
A single line with an -bit binary string representing the answer.
2 3
10
3 5
111
44 1145141919810
00011000111111010000001001001000000001100011
Hint
[Sample 1 Explanation]
The 2-bit Gray Code is: 00, 01, 11, 10, numbered from , so string number 3 is 10.
[Sample 2 Explanation]
The 3-bit Gray Code is: 000, 001, 011, 010, 110, 111, 101, 100, numbered from , so string number 5 is 111.
[Constraints]
For of the testdata: .
For of the testdata: .
For of the testdata: .
For of the testdata: , .
Translated by ChatGPT 5