Handong the Salesman!
Time limit1sMemory limit128 MB
Given a tree, start at node 1 and visit m listed nodes in order, summing the tree distances between consecutive stops.
- Level
Medium4 of 10
- Topics
- Graph, Tree, DFS, Prefix sum
- Solved
- No attempts yet
Problem
Handong is a hardworking salesman who travels around the region. In the past he could pick and visit only the cities he wanted, but times have changed and he can no longer do that. Now his company hands him a list of cities to visit, and he must visit them one by one in exactly the order given. Unfortunately, the order the company provides is not optimized at all. Before setting out, Handong wants to know how much time it takes to visit every city in this order.
The cities in Pohang are numbered from to . Handong always starts his trip at city , the Pohang City Hall. Every pair of directly connected cities is joined by a two-way road, and moving between two directly connected cities always takes unit of time. Every city is reachable from city , and the roads never form a cycle; in other words, the cities and roads form a tree.
Handong starts at city and visits the listed cities in the given order. Whenever he travels between two cities he follows the shortest route along the roads. Find the minimum total time Handong needs to visit all of the listed cities in order.
Input
The first line contains the number of cities in Pohang ().
Each of the next lines contains two integers and , meaning that city and city are directly connected by a road (, ).
The next line contains an integer , the number of cities Handong must visit ().
Each of the following lines contains one city number; these are the cities Handong must visit, given in the order he must visit them.
Output
Print on the first line the minimum time Handong needs, starting at city , to visit all of the given cities in order.