Joining Couples#6604

Joining Couples

2 secondi
64 megabyte
Molto difficile

Air traffic regulations in Nlogonia require that each city must register exactly one outbound flight to another city. Passengers can use this flight only in the direction registered, that is, there may be a flight registered from city to city and no flight registered from city to city . Thus, the number of registered flights is equal to the number of cities. This rule, as one can imagine, makes air travel somewhat complicated, but tradition and a strong ruling by the Queen makes any changes difficult. Besides, some companies even make a profit from the problems caused by the rule.

The Association for Couple Matching (ACM) is setting up a new service to help customers find their long lasting soulmates: the Internet Connecting Program for Couples (ICPC). The service consists of computing the minimum total number of flights a couple needs to take to meet one another (perhaps in a city where neither of them lives in). Assuming the couple's starting cities are and , the agency will try to find a city such that is reachable by air travel from both and , and the sum of the number of flights needed to go from to and the number of flights needed to go from to is minimized. Note that may be equal to or or both.

You will be given the list of all available flights, and a list of queries consisting of pairs of cities where the members of a couple live. For each query, you must compute the minimum total number of flights that are needed for them to meet.

Input

Each test case is described using several lines. The first line contains an integer representing the number of cities (2 \le N \le 10^5). Cities are identified by different integers from to . The second line contains integers F_i, where F_i indicates that the registered outbound flight from city is to city F_i (1 \le F_i \le N, F_i \ne i for i = 1, 2, \ldots, N). The third line contains an integer representing the number of queries (1 \le Q \le 10^5). Each of the next lines describes a query with two integers and indicating the couple's starting cities (1 \le A, B \le N). Within each test case, if it is possible to travel by air from city to city , the maximum number of flights needed to do so is 10^4.

Output

For each test case output lines. In the -th line write an integer with the answer to the -th query. If the corresponding couple can meet by air travel, write the minimum total number of flights that the couple must take to meet one another; if it is impossible for the couple to meet by air travel, write the number ''.

Esempi

Esempio 1

Loading
Loading