Sorting Game
Time limit1sMemory limit1024 MB
After each swap of two positions, find the minimum rounds Aizan needs to sort the permutation while Ermac delays, or -1 if Ermac can always prevent sorting.
- Level
Hard8 of 10
- Topics
- Array, Math, Game theory
- Solved
- No attempts yet
Problem
Ermac and Aizan play a game with a sequence of length . Each integer from 0 to appears exactly once in . The goal of the game is to sort the sequence in ascending order. Aizan tries to sort it, and Ermac tries to keep it unsorted for as long as possible when that cannot be avoided.
In one game, each round Ermac picks two numbers and swaps their positions, and then Aizan picks two numbers and swaps their positions. Both Ermac and Aizan may pick the same number twice so that nothing moves. If the sequence is sorted in ascending order at the end of a round, the game ends. If the sequence is already sorted at the start, the number of rounds needed is 0.
To play several games, Ermac and Aizan modify times and play a game after each change. Two arrays and of length are given. Games are numbered from 0 to in the order they are played. Before game starts, the numbers at positions and of the sequence from the moment game started are swapped, and game is played on the resulting sequence. The sequence at the moment game started is defined as .
For each game, determine whether Aizan is guaranteed to sort the sequence after some number of rounds. If so, find the minimum number of rounds needed.
Input
The first line contains ().
The second line contains the numbers of the sequence , separated by spaces.
The third line contains ().
Each of the next lines contains and , separated by a space ().
Output
For each of the games, in the order the games are played, print if the game can continue indefinitely. Otherwise, print the minimum number of rounds needed. Separate the values with spaces.