beecrowd | 1302
# Joining Couples

**Timelimit: 3**

By Ray Williams Robinson Valiente, UCI Cuba

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 X to city Y and no flight registered from city Y to city X. 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 each other (perhaps in a city where neither of them lives in). Assuming the couple's starting cities are **A** and **B**, the agency will try to find a city **C** such that **C** is reachable by air travel from both **A** and **B**, and the sum of the number of flights needed to go from** A** to **C** and the number of flights needed to go from **B** to** C** is minimized. Note that **C** may be equal to **A** or **B** or both.

It will be given to you 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.

Each test case is described using several lines. The first line contains an integer **N** representing the number of cities ( 2 ≤ **N** ≤ 10^{5}). Cities are identified by different integers from 1 to **N**. The second line contains **N** integers **F**_{i}, where **F**_{i }indicates that the registered outbound flight from city i is to city **F*** _{i}* ( 1 ≤

For each test case output **Q** lines. In the i-th line write an integer with the answer to the i-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 '-1'.

Sample Input | Sample Output |

3 |
1 |