PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#LCA0000023. Số bước dịch chuyển đến đích (Planets Queries II)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Số bước dịch chuyển đến đích (Planets Queries II)

Planets Queries II

Source: CSES

Version: Phuoc Hung OJ Extended

Problem Statement

There are nn planets indexed from 11 to nn. Each planet uu has one directed teleporter to fuf_u.

For each query (a,b)(a,b), start at aa and try to reach bb by following available teleporters. You may take any number of teleports, but cannot reverse them.

Find the minimum number of teleports needed to reach bb, or -1 if it is impossible. When a=ba=b, the answer is 00.

Input

  • The first line contains n,qn,q.
  • The second line contains nn integers f1,…,fnf_1,\ldots,f_n.
  • The next qq lines contain two planet indices a,ba,b.

Output

Print one result per line, or -1 if the destination is unreachable.

Subtasks

  • Subtask 1 (20 points): n≤30n\le30; q≤60q\le60; 1≤n,q≤2⋅1051\le n,q\le2\cdot10^5; 1≤fi,a,b≤n1\le f_i,a,b\le n.
  • Subtask 2 (30 points): n≤1000n\le1000; q≤3000q\le3000; 1≤n,q≤2⋅1051\le n,q\le2\cdot10^5; 1≤fi,a,b≤n1\le f_i,a,b\le n.
  • Subtask 3 (50 points): 1≤n,q≤2⋅1051\le n,q\le2\cdot10^5; 1≤fi,a,b≤n1\le f_i,a,b\le n.

Examples

Input

5 3
2 3 2 3 2
1 2
1 3
1 4

Output

1
2
-1

Explanation

From planet 11, planet 22 is one teleport away and planet 33 two teleports away. Planet 44 cannot be reached by following teleporters from 11.