CF BUDDY
← Problems·

1975D · Paint the Tree

1700 · brute force, dfs and similar, dp

Problem: 378QAQ has a tree with nn vertices. Initially, all vertices are white.

There are two chess pieces called PAP_A and PBP_B on the tree. PAP_A and PBP_B are initially located on vertices aa and bb respectively. In one step, 378QAQ will do the following in order:

  1. Move PAP_A to a neighboring vertex. If the target vertex is white, this vertex will be painted red.
  2. Move PBP_B to a neighboring vertex. If the target vertex is colored in red, this vertex will be painted blue.

Initially, the vertex aa is painted red. If a=ba=b, the vertex aa is painted blue instead. Note that both the chess pieces must be moved in each step. Two pieces can be on the same vertex at any given time.

378QAQ wants to know the minimum number of steps to paint all vertices blue.

Input Format: Each test contains multiple test cases. The first line contains the number of test cases tt (1t1041\leq t\leq 10^4). The description of the test cases follows.

The first line of each test case contains one integer nn (1n21051\leq n\leq 2\cdot 10^5).

The second line of each test case contains two integers aa and bb (1a,bn1\leq a,b\leq n).

Then n1n - 1 lines follow, each line contains two integers xix_i and yiy_i (1xi,yin1 \le x_i,y_i \le n), indicating an edge between vertices xix_i and yiy_i. It is guaranteed that these edges form a tree.

It is guaranteed that the sum of nn over all test cases does not exceed 21052\cdot 10^5.

Output Format: For each test case, output the minimum number of steps to paint all vertices blue.

Note: In the first test case, 378QAQ can paint all vertices blue in the following order:

  • Initially, PAP_A is located on the vertex 11, and PBP_B is located on the vertex 22. The vertex 11 is painted red and the vertex 22 is white.
  • 378QAQ moves PAP_A to the vertex 22 and paints it red. Then 378QAQ moves PBP_B to the vertex 11 and paints it blue.
  • 378QAQ moves PAP_A to the vertex 11. Then 378QAQ moves PBP_B to the vertex 22 and paints it blue.

Sample Cases

Case 1

Input

3
2
1 2
1 2
5
1 2
1 2
1 3
1 4
1 5
8
5 4
7 1
1 5
1 8
8 3
7 2
8 6
3 4

Output

2
8
13

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