Post Office

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

요약
각 우체국이 한 번에 패키지 하나만 보내는 함수형 그래프에서 모든 패키지를 목적지로 보낼 수 있는지 판정하고, 마지막 도착 시간의 최솟값을 구한다.
난이도

어려움10점 중 8점

유형
그래프, 그리디, 동적 계획법, 이분 탐색
정답자
아직 제출이 없습니다

문제

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 P_iP\_i. Note that it is possible for P_i=iP\_i = i. If a package is sent from post office ii at time tt, it will arrive at post office P_iP\_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 A_jA\_j at time 00, and it must eventually be delivered to the assigned post office B_jB\_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

P_1P\_1 P_2P\_2 ⋯\cdots P_NP\_N

MM

A_1A\_1 B_1B\_1

A_2A\_2 B_2B\_2

⋮\vdots

A_MA\_M B_MB\_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.

제한

  • 2≦N≦200,0002 ≦ N ≦ 200\\, 000.
  • 1≦M≦200,0001 ≦ M ≦ 200\\, 000.
  • 1≦P_i≦N1 ≦ P\_i ≦ N (1≦i≦N1 ≦ i ≦ N).
  • 1≦A_j,B_j≦N1 ≦ A\_j, B\_j ≦ N (1≦j≦M1 ≦ j ≦ M).
  • A_j≠B_jA\_j \ne B\_j (1≦j≦M1 ≦ j ≦ M).
  • Given values are all integers.

예제6

  1. 예제 1

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

    입력
    3
    2 1 3
    1
    1 3
    
    예상 출력
    -1
    
  3. 예제 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
    4 1 2 3
    4
    4 1
    4 1
    2 3
    2 3
    
    예상 출력
    4
    
  5. 예제 5

    입력
    7
    1 1 1 3 3 4 4
    5
    6 1
    6 3
    7 1
    5 1
    5 1
    
    예상 출력
    5
    
  6. 예제 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