Official Analysis (C++ and Java)
Explanation
If the cow in position moves to position after one shuffle, then after that shuffle the cow sitting at must have come from .
To undo a single shuffle, for each current position we find the unique satisfying and move the cow at back to . Repeating this step three times recovers the original ordering before any shuffles.
Implementation
Time Complexity:
SHUFFLE_NUM = 3with open("shuffle.in") as read:n = int(read.readline())shuffle = list(map(int, read.readline().split()))ids = list(map(int, read.readline().split()))for _ in range(SHUFFLE_NUM):past_order = [0] * nfor i in range(n):
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!