Official

F - Robot Rotation Editorial by en_translator


The robot can move in either the positive or negative direction of the \(y\) axis in the odd-numbered move, and of the \(x\) axis in the even-numbered move. Also, by choosing the rotation direction appropriately, it can always choose whichever direction, positive or negative. Thus, the even- and odd-numbered operations can be considered as independent one-dimensional problems, and it is sufficient to solve the following problem:

“You are given a length-\(K\) sequence \((B_i)\) of positive integers. You can freely alter the sign of each element of \(B_i\). Find a way to do so so that the sum of the elements becomes \(X\).”

This problem can be solved with the meet-in-the-middle technique in \(O(K 2^{K/2})\) time. First, forget about the construction and consider the decision problem: “is it possible to make the sum \(K\)?”
Enumerate all combinations of the signs of the first \(K/2\) terms, and store the sum for all the cases in a set \(S\). We also compute a set \(T\) for the last \(K/2\) terms in the same way.
The answer is yes if and only if there is an element of \(s\) in \(S\) such that \(X-s\in T\). One can determine the existence for each \(s\) in \(O(\log|T|)\) time, so the decision problem has been solved in \(O(|S|\log|T|)=O(K2^{K/2})\) time.
Same applies to when we need to determine the actual combination of the signs; instead of storing \(S\) and \(T\) as sets, we maintain a dict whose keys are the sums and values are the combinations of the signs.

Therefore, the problem has been solved in a total of \(O(N2^{N/4})\) time.

posted:
last update: