10463: USACO 2024 US Open Contest, Bronze Problem 3. Farmer John's Favorite Permutation
Description
Let the remaining elements of $p$ be $p'_1, p'_2, \dots , p'_n$,
- If $p'_1 > p'_n$, he writes down $p'_2$ and removes $p'_1$ from the permutation.
- Otherwise, he writes down $p'_{n-1}$ and removes $p'_n$ from the permutation.
At the end, Farmer Nhoj will have written down $N - 1$ integers $h_1, h_2, \dots, h_{N-1}$, in that order. Given $h$, Farmer John wants to enlist your help to reconstruct the lexicographically minimum $p$ consistent with Farmer Nhoj's hints, or determine that Farmer Nhoj must have made a mistake. Recall that if you are given two permutations $p$ and $p'$, $p$ is lexicographically smaller than $p'$ if $p_i < p'_i$ at the first position $i$ where the two differ.
Input
The first line contains $N$.
The second line contains $N - 1$ integers $h_1, h_2, \dots, h_{N-1}$ ($1\le h_i\le N$).
Output
If there is a permutation $p$ of $1\dots N$ consistent with $h$, output the lexicographically smallest such $p$. If no such $p$ exists, output $-1$.
Constraints
- Input 2: $N\le 8$
- Inputs 3-6: $N\le 100$
- Inputs 7-11: No additional constraints.
Sample 1 Input
5
2
1
2
2
4
1 1 1
4
2 1 1
4
3 2 1
Sample 1 Output
1 2
-1
-1
3 1 2 4
1 2 3 4
p' = [3,1,2,4] p_1' < p_n' -> h_1 = 2 p' = [3,1,2] p_1' > p_n' -> h_2 = 1 p' = [1,2] p_1' < p_n' -> h_3 = 1 p' = [1]
Note that the permutation $p=[4,2,1,3]$ would also produce the same $h$, but $[3,1,2,4]$ is lexiocgraphically smaller.
For the second test case, there is no $p$ consistent with $h$; both $p=[1,2]$ and $p=[2,1]$ would produce $h=[1]$, not $h=[2]$.