Smallest LNR Sequence
Time limit1sMemory limit128 MB
Given n and a binary string s, find the position of s in the lexicographically smallest de Bruijn sequence of order n.
Problem
An -bit shift register is a memory that holds bits, and its contents can be changed in only two ways. The contents are shifted left by one position, and the rightmost bit is given a 0 or a 1. One such change is called a move. For example, when the contents of a 4-bit shift register are 0001, one move makes the contents either 0010 (a 0 is shifted in) or 0011 (a 1 is shifted in).
Start from an -bit shift register whose contents are all zeroes. Build a sequence of moves so that after every move the contents differ from all past contents. An -bit shift register has possible contents, so the longest such sequence has length . For every , at least one sequence of length exists. For there are two sequences of length .
= 000 001 010 101 011 111 110 100
= 000 001 011 111 110 101 010 100
LNR (Longest Non-Repeating) sequences
Given a positive integer , consider any sequence with the following five properties.
- Each element of the sequence is a bit-string of length .
- The sequence has elements.
- No element repeats.
- All bits of the first element are zero.
- Every element other than the first comes from the element before it by one move as described above.
Such a sequence is a Longest-Non-Repeating sequence, or LNR sequence. For a positive integer , the set of all LNR sequences is written .
The smallest LNR sequence
An LNR sequence gets a value as follows. Concatenate the bit-strings of into a single bit-string, then read that bit-string as a binary number. For the LNR sequence above,
= 000001010101011111110100
The smallest LNR sequence is the sequence in with the smallest . For the only LNR sequences are and , and , so . The positions of the bit-strings 000, 001, 010, 101, 011, 111, 110, 100 in are 1, 2, 3, 4, 5, 6, 7, 8 respectively.
What you need to do
Given a positive integer and a bit-string of length , compute and print the position of in it. Print 1 if is the first element of , print 2 if it is the second element, and so on.
Input
The input has two lines. The first line contains a positive integer . The second line contains a bit-string of length .
Output
Print a single positive integer, the position of in .
Hint
Do not construct all LNR sequences and then pick the smallest one. You can find the smallest LNR sequence by trying the move that shifts in a 0 before the move that shifts in a 1.