#K64292. Seating Arrangement Problem

    ID: 31943 Type: Default 1000ms 256MiB

Seating Arrangement Problem

Seating Arrangement Problem

You are given n guests numbered from 0 to n-1 and an array of n integers partners such that partners[i] indicates the partner of the guest i. Your task is to arrange these guests in a circle (i.e. the arrangement is considered cyclic) satisfying the following constraints for every adjacent pair (including the pair formed by the last and the first guest):

  • The two guests must not be partners. In other words, if guest a is immediately followed by guest b then b must not equal partners[a].
  • The two guests must not be consecutive numbers in a cyclic modulo sense; that is, if guest a is immediately followed by guest b then it must not be that \(b \equiv a+1 \pmod{n}\).

If such an arrangement exists, output the lexicographically smallest valid arrangement (when viewed as a sequence, with the 0th guest fixed as the first element). Otherwise, output -1.

Note: Two constraints appear similar; however, they enforce conditions on different aspects of the seating arrangement. Use backtracking or brute-force search to generate the arrangement. The formulas used in the constraints are shown in \(\LaTeX\) below:

For every adjacent pair \((a, b)\), ensure that \[ b \neq partners[a] \quad \text{and} \quad b \neq (a+1) \mod n. \]

inputFormat

The input is given via standard input and consists of two lines:

  • The first line contains a single integer n representing the number of guests.
  • The second line contains n space-separated integers where the i-th integer represents partners[i].

outputFormat

If a valid seating arrangement exists, output a single line with n space-separated integers representing the seating order (starting with guest 0). Otherwise, output a single line with -1.

## sample
6
1 0 3 2 5 4
0 2 4 1 5 3

</p>