Safe Unlock Code
Time limit1sMemory limit128 MB
For each n, print the lexicographically smallest de Bruijn sequence of order n over the digits 0 to 9, whose length is 10^n + n - 1.
- Level
Medium7 of 10
- Topics
- Graph, DFS, Greedy, Implementation
- Solved
- No attempts yet
Problem
KEY Inc., a leading maker of security hardware, has built a new kind of safe. To open it you do not use a key; instead you must type the correct -digit code on a keypad. Models range from toy safes for children (a 2-digit code) up to the military version (a 6-digit code).
The safe opens the instant the last digit of the correct code is entered — there is no "Enter" key. If you type more than digits, only the last digits matter. For example, in the 4-digit version, if the correct code is 4567 and you type the sequence 1234567890, the door opens the moment you press 7.
Internally the safe is always in one of states, where the current state is simply the last digits entered. One of these states (456 in the example) is marked as the unlocked state. If the safe is in the unlocked state and the correct next key (7 in the example) is pressed, the door opens; otherwise the safe moves to a new state. For example, from state 456, pressing 8 moves the safe to state 568.
A naive way to open the safe is to try every code in turn, which in the worst case needs keystrokes. With a well-chosen digit sequence, however, you can guarantee the safe opens after at most keystrokes: all you need is a digit sequence that contains every -digit sequence exactly once.
Input
The input contains several test cases. Each test case is a single integer with . The last test case is followed by a line containing 0, which must not be processed.
Output
For each test case , print a single line: the lexicographically smallest sequence of digits (each digit 0–9) in which every -digit sequence occurs exactly once as a contiguous substring.