Decoding the Rotary Encoder
A robot arm's joint is fitted with an absolute rotary encoder. The encoder divides one full turn of
the shaft into 2^b positions, numbered 0 to 2^b − 1 in the forward direction; after position
2^b − 1 comes position 0 again. Instead of plain binary, the encoder disk is printed with a
reflected Gray code, so that only one track changes between neighbouring positions: the reading for
position p is the b-bit binary representation of p XOR (p >> 1), most significant bit first
(>> is a right shift by one bit).
The controller logged n consecutive readings and you are writing the tool that turns the log into
something people can read. First, decode every reading into its position. Second, estimate how the
shaft moved. Between two consecutive readings the shaft is assumed to have taken the shorter way
around the circle: going from position p to position q, let d = (q − p) mod 2^b, a value in
[0, 2^b).
- If
d < 2^(b−1), the shaft moveddsteps forward (a step of+d). - If
d > 2^(b−1), the shaft moved2^b − dsteps backward (a step of−(2^b − d)). - If
d = 2^(b−1)exactly, both ways are equally long; the controller counts it as2^(b−1)steps forward.
Report the net rotation (the sum of all signed steps) and the total travel (the sum of their absolute values).
Input
The first line contains two integers n and b (1 ≤ n ≤ 10^5, 1 ≤ b ≤ 60).
Each of the next n lines contains one reading: a string of exactly b characters, each 0 or 1,
most significant bit first.
The input is guaranteed to be such that the total travel does not exceed 10^18.
Output
Print n lines: the i-th of them contains the position decoded from the i-th reading, as a
decimal integer.
Then print one more line with two integers: the net rotation and the total travel, in steps. The net
rotation is negative if the shaft moved backward more than forward. If n = 1, both are 0.
Notes
In the first example the code-to-position table for b = 3 is 000 → 0, 001 → 1, 011 → 2,
010 → 3, 110 → 4, 111 → 5, 101 → 6, 100 → 7. The positions are 0, 1, 2, 7, 6, 3. The
steps are +1, +1, then 2 → 7 is 3 steps backward (wrapping through 0) rather than 5
forward, then −1, and finally 6 → 3 is −3. The net rotation is −5 and the total travel is
9.
In the second example the positions are 0, 8, 15, 0 on a circle of 16. Going from 0 to 8 is
exactly half a turn, which counts as +8; then +7 and +1 (from 15 across to 0). The shaft
made one full forward turn.