Baralho Alho

시간 제한1초메모리 제한2048 MB

요약
고정된 순열을 k번 적용해 덱 A를 덱 B로 만드는 최소 k를 구하고, 불가능하거나 1e9를 넘으면 각각 다른 문구를 출력한다.
난이도

보통10점 중 7점

유형
수학, 정수론, 구현, 배열
정답자
아직 제출이 없습니다

문제

Researcher Isadora loves playing cards with her friends. More specifically, she plays a version called Baralho Alho, in which there are NN cards (duplicates are allowed). Initially, the NN cards are in a specific order: the ii-th card has value A_iA\_i. Two cards are considered equal if they have the same value.

Before the game starts, Isadora declares: “I always shuffle Baralho Alho.” Naively, her friends agree and let her command the shuffling. Little do they know that Researcher Isadora loves to cheat. Her goal is to shuffle in such a way that, at the end of the process, the ii-th card has value B_iB\_i.

However, she only knows one type of shuffling: it maps the card originally at position ii to position P_iP\_i. For example, if P=\[3,2,4,1]P = \[3, 2, 4, 1], then the first card goes to the third position, the second remains in place, the third goes to the fourth, and the fourth goes to the first. Thus, if the initial deck is \[4,2,6,1]\[4, 2, 6, 1], after applying the shuffling, Isadora gets \[1,2,4,6]\[1, 2, 4, 6].

Even with this limitation, Isadora is quite intelligent and plans to repeat the shuffling several times in order to reach new deck configurations.

Write a program that, given A_iA\_i, B_iB\_i, and P_iP\_i, determines the minimum number of times Isadora needs to apply the shuffling so that the deck is in the desired order. If this is impossible, print “IMPOSSIVEL” (without quotes). If the minimum number of shuffles is greater than 10910^9, print “DEMAIS” (without quotes).

입력

The first line of input contains an integer NN (1≤N≤1061 ≤ N ≤ 10^6).

The second line contains NN integers A_iA\_i (1≤A_i≤1091 ≤ A\_i ≤ 10^9), representing the initial configuration of the deck.

The third line contains NN integers B_iB\_i (1≤B_i≤1091 ≤ B\_i ≤ 10^9), representing the desired final configuration of the deck.

The fourth line contains NN distinct integers P_iP\_i (1≤P_i≤N1 ≤ P\_i ≤ N), indicating that the card in position ii goes to position P_iP\_i after one application of the shuffling.

출력

Print a single integer kk: the minimum number of times the shuffling must be applied, starting from A_iA\_i, until the resulting configuration is B_iB\_i.

If this is impossible, print “IMPOSSIVEL” (without quotes).

If the minimum kk is greater than 10910^9, print “DEMAIS” (without quotes).

예제5

  1. 예제 1

    입력
    6
    8 6 5 5 1 3
    5 1 8 5 3 6
    2 3 6 5 1 4
    
    예상 출력
    2
    
  2. 예제 2

    입력
    2
    3 3
    3 3
    1 2
    
    예상 출력
    0
    
  3. 예제 3

    입력
    5
    6 3 8 4 2
    3 6 4 2 8
    2 1 4 5 3
    
    예상 출력
    5
    
  4. 예제 4

    입력
    4
    1 2 1 2
    1 2 2 1
    2 1 4 3
    
    예상 출력
    IMPOSSIVEL
    
  5. 예제 5

    입력
    3
    1 2 3
    2 1 4
    1 2 3
    
    예상 출력
    IMPOSSIVEL