Cow Photography

Time limit1sMemory limit128 MB

Summary
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 NN (1≤N≤20,0001 \le N \le 20{,}000) cows are tagged with ID numbers 1…N1 \ldots N. He wants to photograph them standing in one specific order, given by an array A[1…N]A[1 \ldots N], where A[j]A[j] is the ID of the jj-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 AA 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 AA 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 AA. The intended order AA is always uniquely determined.

Input

  • Line 1: the number of cows, NN (1≤N≤20,0001 \le N \le 20{,}000).
  • The next 5N5N lines: five orderings, each given as a block of NN consecutive lines. Each line holds one cow ID, an integer in 1…N1 \ldots N. The ii-th block is the ii-th photograph.

Output

  • NN lines: the intended order AA, 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 AA is uniquely determined, so exactly one correct output exists.

Examples3

  1. Example 1

    Input
    5
    1 
    2 
    3 
    4 
    5
    2
    1
    3
    4
    5
    3
    1
    2
    4
    5
    4
    1
    2
    3
    5
    5
    1
    2
    3
    4
    
    Expected output
    1
    2
    3
    4
    5
    
  2. Example 2

    Input
    1
    1
    1
    1
    1
    1
    
    Expected output
    1
    
  3. Example 3

    Input
    2
    2
    1
    2
    1
    2
    1
    1
    2
    2
    1
    
    Expected output
    2
    1