Salesmen
InterviewTime limit1sMemory limit128 MB
Given a graph and a reported vertex sequence, find the fewest entries to change so consecutive vertices stay put or follow an edge.
- Level
Medium5 of 10
- Topics
- Dynamic programming, Graph
- Solved
- No attempts yet
Problem
Traveling salesmen of a company report their current location to the company on a regular basis. They must also report a new location whenever they move to a different place. The company records each salesman's working path on a map of his working area and uses that path to plan the salesman's next assignment.
The map of a salesman's working area is a connected, undirected graph. Vertices are the possible locations of the salesman and edges are the possible movements between locations. A salesman's working path is therefore a sequence of vertices in the graph.
Because a salesman reports his position regularly and may stay at one place for a very long time, the same vertex can appear several times in a row in a working path. A working path is called correct if, for every pair of consecutive vertices, the two vertices are either the same vertex or two adjacent vertices in the graph.
For example, on the graph below representing a salesman's working area,

the reported working path [1 2 2 6 5 5 5 7 4] is correct, but the reported working path [1 2 2 7 5 5 5 7 4] is not, because there is no edge between vertices and . If we assume that the salesman reports his location every time he is required to (but possibly incorrectly), the intended correct path could be [1 2 2 4 5 5 5 7 4], [1 2 4 7 5 5 5 7 4], or [1 2 2 6 5 5 5 7 4].
The length of a working path is the number of vertices in it. For two paths and of the same length , the distance between them is
where
Given the graph of a salesman's working area and a working path (which may not be a correct path), compute a correct working path of the same length that minimizes , and report that minimum distance.
Input
The first line contains the number of test cases . Each test case has the following format.
The first line of a test case contains two integers and (, ), where is the number of vertices of the graph and is the number of edges. The graph is connected. Vertices are numbered from to .
Each of the next lines contains two vertices describing one edge of the graph.
The last line of the test case describes a working path. The first integer () is the length of the path, followed by integers giving the sequence of vertices along the path.
Output
For each test case, print a single line containing the minimum distance from the given path to a correct path of the same length.