CF BUDDY
← Problems·

1675F · Vlad and Unfinished Business

1800 · dfs and similar, dp, greedy

Problem: Vlad and Nastya live in a city consisting of nn houses and n1n-1 road. From each house, you can get to the other by moving only along the roads. That is, the city is a tree.

Vlad lives in a house with index xx, and Nastya lives in a house with index yy. Vlad decided to visit Nastya. However, he remembered that he had postponed for later kk things that he has to do before coming to Nastya. To do the ii-th thing, he needs to come to the aia_i-th house, things can be done in any order. In 11 minute, he can walk from one house to another if they are connected by a road.

Vlad does not really like walking, so he is interested what is the minimum number of minutes he has to spend on the road to do all things and then come to Nastya. Houses a1,a2,,aka_1, a_2, \dots, a_k he can visit in any order. He can visit any house multiple times (if he wants).

Input Format: The first line of input contains an integer tt (1t1041 \le t \le 10^4) — the number of input test cases. There is an empty line before each test case.

The first line of each test case contains two integers nn and kk (1kn21051 \le k \le n \le 2\cdot 10^5) — the number of houses and things, respectively.

The second line of each test case contains two integers xx and yy (1x,yn1 \le x, y \le n) — indices of the houses where Vlad and Nastya live, respectively.

The third line of each test case contains kk integers a1,a2,,aka_1, a_2, \dots, a_k (1ain1 \le a_i \le n) — indices of houses Vlad need to come to do things.

The following n1n-1 lines contain description of city, each line contains two integers vjv_j and uju_j (1uj,vjn1 \le u_j, v_j \le n) — indices of houses connected by road jj.

It is guaranteed that the sum of nn for all cases does not exceed 21052\cdot10^5.

Output Format: Output tt lines, each of which contains the answer to the corresponding test case of input. As an answer output single integer — the minimum number of minutes Vlad needs on the road to do all the things and come to Nastya.

Note: Tree and best path for the first test case:

12131 \rightarrow 2 \rightarrow 1 \rightarrow 3

Tree and best path for the second test case:

313525653 \rightarrow 1 \rightarrow 3 \rightarrow 5 \rightarrow 2 \rightarrow 5 \rightarrow 6 \rightarrow 5

Tree and best path for the third test case:

3523 \rightarrow 5 \rightarrow 2

Sample Cases

Case 1

Input

3
3 1
1 3
2
1 3
1 2
6 4
3 5
1 6 2 1
1 3
3 4
3 5
5 6
5 2
6 2
3 2
5 3
1 3
3 4
3 5
5 6
5 2

Output

3
7
2

Similar problems

00:00:00
Loading editor…
Welcome! I'm your coding tutor for this problem. Use the chips below to reveal stored hints or get AI feedback on your code. I'll guide you step by step — never giving away the solution.

Sign in to unlock AI tutor feedback