Cow Photography
Time limit1sMemory limit128 MB
Given five permutations of 1..N, each reachable from an unknown target permutation by at most one element removal-and-reinsertion, recover the target permutation.
- Level
Medium7 of 10
- Topics
- Sorting, Implementation, Brute force
- Solved
- No attempts yet
Problem
The cows are feeling especially mischievous today. Farmer John just wants a photograph of his cows standing in a line, but they keep shifting position right before he can press the shutter.
Farmer John's () cows are tagged with ID numbers . He wants to photograph them standing in one specific order, given by an array , where is the ID of the -th cow in that order. He lines the cows up in this order, but just before he can take the picture, up to one cow moves to a new spot in the line. More precisely, either no cow moves, or exactly one cow leaves her current spot and re-inserts herself somewhere else in the line.
Undeterred, Farmer John lines the cows up in the order again, and again, just before the shutter, up to one cow (different from the first) moves. This repeats until he has taken a total of five photographs, and then he gives up.
Each photograph therefore shows the order after up to one cow has moved. Crucially, if a cow chooses to actively move in one photograph, she does not actively move in any of the other four (although she may still end up in a different position because other cows moved around her).
Given all five photographs, reconstruct the intended order . The intended order is always uniquely determined.
Input
- Line 1: the number of cows, ().
- The next lines: five orderings, each given as a block of consecutive lines. Each line holds one cow ID, an integer in . The -th block is the -th photograph.
Output
- lines: the intended order , one cow ID per line, from the front of the line to the back.
Notes
- In every photograph at most one cow actively changes position, and any cow that actively moves does so in exactly one of the five photographs.
- Under these rules the intended order is uniquely determined, so exactly one correct output exists.