Travel
Time limit1sMemory limit1024 MB
Yan walks a tree by always taking the first road in each city's list and moving that road to the end. Find the earliest day he visits all friends in order.
- Level
Medium7 of 10
- Topics
- Tree, Simulation, DFS
- Solved
- No attempts yet
Travel
Yan enjoys travelling around the country of Iatiland in his car.
Since Yan has been travelling for a long time, he has come up with a description of the map of the whole country. The cities in Iatiland are numbered from to , and there are bi-directional direct roads connecting pairs of different cities. For each city, he has a list of cities that are reachable from it using a direct road. It is guaranteed that there is a unique path between every pair of cities. Note that the path may not be direct, i.e. it may use several direct roads. This means that there are a total of direct roads.
Yan likes travelling systematically, so he follows an algorithm while going around the country.
He starts his journey in city on day . Every subsequent day he follows a direct road from the city he is currently in. The road he chooses is always the first road in the list of the current city. After picking the road, he removes it from the beginning of the list and appends it to the end.
Yan's main objective is to meet his friends and gossip with them. He has friends, numbered from to , and friend lives in city . He can visit friend only when he is currently in city . Yan wants to visit his friends in the given order, so he cannot visit friend before visiting friend .
Find the minimal number of days before he visits all of his friends in the correct order.
Input
The first line contains two numbers and .
This is followed by lines. On line , there is , the number of direct paths coming out of city , followed by numbers, the initial list of cities to which city is connected by a direct path.
The last line contains numbers , the cities where Yan's friends live.
Output
Output the minimum number of days on a single line.