Acquapia
Time limit1sMemory limit128 MB
Multiple test cases give several river trees; for each city pair, report whether a route exists and, if so, the unique city where the ship must switch from upstream to downstream.
- Level
Medium7 of 10
- Topics
- Tree, DFS, Implementation, Graph
- Solved
- No attempts yet
Problem
Acquapia is a small country crossed by several navigable rivers. Every river has its source in the mountains inside Acquapia and eventually flows into the sea; a river never flows into another river. Along its course (but not at its source) a river may split into two or more streams. There is a city at every point where a river begins, splits, or ends, and each city touches at most one river.
Rivers are the main means of transportation in Acquapia. Because the country is at war, ships cannot cross the sea and may travel only along rivers. To move between two cities a ship travels upstream (against the flow) up to some city, performs a stream change there, and then travels downstream (with the flow) to the destination. A stream change — switching from upstream to downstream navigation — is difficult and dangerous, so it should be avoided when possible; when it is unavoidable, it happens at exactly one city on the route. Travelling purely upstream or purely downstream needs no stream change.
Each river forms a tree rooted at its source with edges oriented downstream, so the route between any two connected cities is unique; hence the stream-change city, if any, is uniquely determined.
Given the rivers, the cities, and a list of queries, each a pair of cities and , answer for every query:
- Is it possible to navigate from city to city ?
- If it is, does the ship need a stream change, and if so, at which city?
Input
The input contains several test cases. The first line of each test case has four integers , , and separated by single spaces: the number of cities (), the number of rivers (), the number of river sections () and the number of queries (). Cities are numbered from to .
The second line contains distinct integers, the cities that are river sources. Each of the next lines contains two integers and (), meaning there is a river section flowing from city down to city . Each of the following lines contains two integers and (), a query.
The end of the input is the line , which must not be processed.
Output
For each test case, print lines; the -th line is the answer to the -th query, in input order. Print a single empty line between the outputs of two consecutive test cases.
For a query print:
- if it is impossible to navigate from to ;
- if navigation is possible without any stream change;
- otherwise, the number of the city where the stream change must be made.