Tag on the Tree

medium dfs trees graphs games 2000 ms · 256 MB

Tag on the Tree

Alice and Bob are playing tag in a treehouse complex of n rooms connected by n - 1 corridors, forming a tree. Alice starts in room 1. Bob starts in room x (x ≠ 1), having snuck away from Alice's favorite starting spot.

The two take turns, Bob moving first. On a turn, the player whose turn it is either stays in their current room or walks along one corridor to a room adjacent to their current room. The game ends the instant Alice's move brings her into the room Bob currently occupies — that is, only Alice's arrival in Bob's room ends the game; if Bob's move happens to bring him into Alice's room, nothing special happens and play continues. (Optimal play means Bob never actually does this.)

Bob wants the game to last as long as possible; Alice wants to end it as quickly as possible. Both play optimally, and both always know where the other currently is. Counting every turn made by either player (including turns where someone just stays put), how many turns will the game last?

Input

The first line contains two integers n and x (2 ≤ n ≤ 2·10^5, 2 ≤ x ≤ n) — the number of rooms and Bob's starting room.

Each of the next n - 1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v) describing a corridor directly connecting room u and room v. The corridors form a tree on the n rooms.

Output

Print a single integer: the total number of turns (Bob's and Alice's combined) until Alice catches Bob, assuming both play optimally.

Notes

In the first example, Bob starts right next to Alice. His best option is to simply wait: he stays put on his turn, and Alice immediately walks in and catches him, for a total of 2 turns.

In the second example, Bob is at the middle of a path and can outrun Alice toward the far end before she can cut him off, making the chase last longer than in the first example.

Example 1

Input

2 2
1 2

Output

2

Example 2

Input

5 3
1 2
2 3
3 4
4 5

Output

8

Hints · reveal one at a time if you're stuck

Hint 1

Start with the simplest case where Bob begins right next to Alice. Why would Bob be best off standing still there, and what does that suggest about where Bob should aim to go?

Hint 2

Suppose Bob walks to some room v and waits there. Which rooms can he reach strictly before Alice could get there, and how long does Alice then take to reach him?

Hint 3

Compute the distance from room 1 and from Bob's start to every room with two traversals of the tree, then choose the best room that Bob reaches strictly before Alice. Bob moves first in each round, so count both players' turns, and use an iterative traversal since the tree can be a long path.

report an issue Prefer your own editor? sooks prep 67 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.