Under construction

Still being built. Things may change

Portals

Interview

Time limit1sMemory limit1024 MB

Summary
Each portal leads to exactly one destination, and for each query the task is to count the jumps from start s to end e, or report -1 if e is never reached.
Level

Medium5 of 10

Topics
Graph, Tree, DFS
Solved
No attempts yet

Problem

The new company Sveriges Portaltrafik wants to change how Swedish commuters travel around the country. The company has proposed building a portal system in Sweden that uses fuel-efficient portals to replace trains, planes, and buses. The government has been asked to review the proposal in detail and has asked Swedish elite programmers for help. That is where you come in.

The portal system consists of NN portals placed at various locations in the country. Each portal aa has a destination portal bb. This means that each time you enter aa, you come out of bb. Entering bb does not necessarily bring you back to aa.

For a number of given start and end portals aa and bb, the government wants to know how many times you need to enter the portal you emerge from to get from aa to bb, or whether it is possible at all. For each query, answer with the number of times you need to enter portals to get from aa to bb. If it is impossible, answer −1-1.

Input

The first line contains the integer NN, the number of portals. The next NN lines each contain an integer 1≤di≤N1 \le d_i \le N, meaning that portal ii leads to portal did_i. Portals are numbered from 1 to NN, and they appear in the input in that order.

The next line contains the integer QQ, the number of queries. The following QQ lines each contain two integers 1≤s,e≤N1 \le s, e \le N, giving a start portal ss and an end portal ee. For every query, s≠es \neq e.

Output

Print QQ lines, one answer per query: the number of times you need to pass through portals to get from the start portal to the end portal. If it is impossible, print −1-1. Print each answer on its own line.

Constraints

1≤N≤50 0001 \le N \le 50\,000

1≤Q≤70 0001 \le Q \le 70\,000

Hint

The figure shows the network of the sample input. There are three queries. The first asks how many times you need to enter portals when you start at 1 and want to reach 2. Entering 1 takes you directly to 2, so the answer is 1. Getting from 1 to 4 takes three jumps. The answer to the last query is −1-1, because starting from 2 you can never reach 5, no matter how many times you pass through portals.

Examples1

  1. Example 1

    Input
    5
    2
    3
    4
    3
    4
    3
    1 2
    1 4
    2 5
    
    Expected output
    1
    3
    -1