Joining Couples
Time limit1sMemory limit128 MB
Each city has one directed outbound flight, forming a functional graph; for each query find the minimum combined distance from two starting cities to any common reachable city, or -1.
- Level
Hard8 of 10
- Topics
- Graph, Tree, Binary search, Prefix sum
- Solved
- No attempts yet
Problem
Nlogonia's air-traffic rules require every city to register exactly one outbound flight to another city. A flight may be used only in its registered direction: a registered flight from city to city does not imply a flight from to . Because every city registers exactly one outbound flight, the total number of registered flights equals the number of cities.
The Association for Couple Matching runs a service that computes the minimum total number of flights a couple must take in order to meet, possibly in a city where neither of them lives. If the two people start in cities and , the service looks for a city that is reachable by air from both and and minimizes the sum of the number of flights needed to go from to and the number of flights needed to go from to . City may be equal to , to , or to both.
You are given the list of all registered flights together with several queries, each giving the two cities where the members of a couple live. For each query, compute the minimum total number of flights the couple needs in order to meet.
Input
The input contains several test cases and ends at end of file.
Each test case is described on several lines:
- The first line contains an integer , the number of cities (). Cities are numbered from to .
- The second line contains integers , where is the city that the single outbound flight registered from city goes to ( and ).
- The third line contains an integer , the number of queries ().
- Each of the next lines contains two integers and , the cities where the members of one couple live ().
Within a single test case, whenever it is possible to travel by air from a city to a city , the number of flights needed to do so is at most .
Output
For each query, output one line. If the couple can meet by air travel, print the minimum total number of flights they must take to meet; if they can never meet, print . Print the answers for all test cases, in order.