PivotOJ

Post Office

시간 제한: 2000ms메모리 제한: 2048MB출처: JOI 2024-2025 본선BOJ 33728

문제

In the JOI country, there are NN post offices, numbered from 11 to NN. Each post office has an assigned ”destination,” and the destination of post office ii is post office PiP_i. Note that it is possible for Pi=iP_i = i. If a package is sent from post office ii at time tt, it will arrive at post office PiP_i at time t+1t + 1. However, a post office cannot send another package while it is in the process of sending a package. Each post office can store an unlimited number of packages at any given time.

Now, MM packages need to be delivered in the JOI country. The jj-th package arrives at post office AjA_j at time 00, and it must eventually be delivered to the assigned post office BjB_j. Given the information about the post offices and the packages, write a program to determine whether it is possible to deliver all the packages to their assigned post offices, and if so, find the smallest possible time at which the last package arrives at its assigned post office.

입력

Read the following data from the standard input.

NN

P1P_1 P2P_2 \cdots PNP_N

MM

A1A_1 B1B_1

A2A_2 B2B_2

\vdots

AMA_M BMB_M

출력

Output a single line to the standard output. If it is possible to deliver all the packages to their assigned post offices, output the smallest possible time at which the last package arrives at its assigned post office. Otherwise, output -1 instead.

예제

예제 1

입력
5
1 1 2 3 4
3
3 2
3 1
3 1
출력
3

예제 2

입력
3
2 1 3
1
1 3
출력
-1

예제 3

입력
7
1 1 2 3 4 5 6
6
4 2
5 1
5 3
6 2
7 3
7 6
출력
5

예제 4

입력
4
4 1 2 3
4
4 1
4 1
2 3
2 3
출력
4

예제 5

입력
7
1 1 1 3 3 4 4
5
6 1
6 3
7 1
5 1
5 1
출력
5

예제 6

입력
11
3 1 2 5 6 7 8 4 4 5 10
6
2 1
9 8
11 8
10 4
5 6
5 7
출력
6
코드를 제출하려면 로그인하세요.