Table of Contents

ExplanationImplementation

Official Analysis (C++ and Java)

Explanation

If the cow in position ii moves to position aia_i after one shuffle, then after that shuffle the cow sitting at aia_i must have come from ii.

To undo a single shuffle, for each current position jj we find the unique ii satisfying ai=ja_i = j and move the cow at jj back to ii. Repeating this step three times recovers the original ordering before any shuffles.

Implementation

Time Complexity: O(N)\mathcal{O}(N)

SHUFFLE_NUM = 3
with 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] * n
for 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!