A rainforest research station connects its treehouses with a network of rope bridges. There are n treehouses, numbered 0 to n-1, joined by exactly n-1 bridges so that every treehouse is reachable from every other treehouse and no bridge forms a cycle (the network is a tree). Rangers have equipped a contiguous chain of treehouses -- a beacon trail -- with emergency beacons: the trail is given as a sequence of k treehouse numbers where each consecutive pair in the sequence is directly joined by a bridge, and no treehouse appears twice in the sequence.
For each of q outpost treehouses, you must report the beacon treehouse that is nearest to it, where distance is measured as the number of bridges crossed on the unique path between two treehouses. If more than one beacon treehouse is tied for nearest, report the one with the smallest treehouse number.
n.n-1 lines contains two integers u v, describing a bridge between treehouses u and v.k, the length of the beacon trail.k integers, the treehouse numbers of the beacon trail in order (consecutive entries are directly bridge-connected, no repeats).q, the number of outposts.q integers, the treehouse numbers of the outposts to answer for.Print q integers separated by single spaces on one line: for each outpost (in the given order), the number of its nearest beacon treehouse.
1 <= n <= 20001 <= k <= n1 <= q <= 2000[0, n-1].n-1 bridges form a connected tree with no repeated or self-loop edges.Example 1
Input
6 0 1 1 2 2 3 3 4 1 5 3 1 2 3 3 0 4 5
Expected
1 3 1
Explanation
Treehouses 1, 2, 3 form the beacon trail. Treehouse 0's only bridge leads to beacon 1 (distance 1), so its answer is 1. Treehouse 4's only bridge leads to beacon 3 (distance 1), so its answer is 3. Treehouse 5's only bridge leads to beacon 1 (distance 1), so its answer is 1. Output: 1 3 1.
Example 2
Input
1 1 0 1 0
Expected
0
Explanation
There is only one treehouse (n=1, no bridges). The beacon trail is just [0], and the single outpost is 0 itself, at distance 0 from the only beacon. Output: 0.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →