Shuffling#3139

Shuffling

3 seconds
64 megabytes
Hard

A casino owns an expensive card shuffling machine which can shuffle up to cards at a time (there are cards in each deck). For convenience, we will label the cards 1, 2, 3, \ldots, N, where is the total number of cards, and copies of the same card (e.g., Ace of Spades) from different decks are considered different. Unfortunately, the card shuffling machine is defective and always shuffles the cards in the same way. The company that produces these machines is out of business due to the economic downturn. There is no one to repair the machine, and a new machine is too expensive.

As a brilliant casino employee, you realize that not all is lost. By using the machine zero or more times, you can shuffle the cards differently. For example, suppose the machine shuffles the cards 1, 2, 3, 4 into the order 2, 3, 4, 1. If you put the cards into the machine, take the shuffled cards out and insert them again (without changing the order), you will get the order 3, 4, 1, 2. In this way, it is possible to shuffle the cards in many different patterns, even though it may take longer. But this is not a significant issue as decks do not have to be reshuffled often, and used decks can be shuffled while other decks are being used to avoid any waiting time.

Unfortunately, not all shufflings can be produced in this manner, and you wish to know if this procedure could "stack the decks" in favor of the casino or the player. As a first step, you want to know which shufflings can be produced, and how many times you need to use the machine on the deck in order to produce the shuffling.

Input

The input for each case consists of three lines. The first line contains a single integer , the number of cards to shuffle. The number of cards is a positive integer up to . The second line contains the integers 1, 2, \ldots, N listed in some order and separated by spaces. The list gives the order of the shuffling performed by the machine when the input cards are ordered 1, 2, \ldots, N. The third line, in the same format as the second, gives the shuffling you wish to obtain. The end of input is indicated by a line in which N = 0.

Output

For each case, print the smallest number of times (zero or more) you need to pass the deck through the machine to produce the desired shuffling. If it is not possible, print "-1". The output for each case should be a single line. You may assume that the answer will always fit in a -bit signed integer.

Examples

Example 1

Loading
Loading