On a tree with home at node 1 and office at node n, find the smallest flashlight range d so that a random walk governed by visibility rules always reaches home within 10^9 steps.
Hard8TreeDFSGreedyGraphNo attempts yetTime limit2sMemory limit512 MBArman recently moved to a remote village in the countryside. The map of the village is a tree: exactly n−1 roads connect n intersections, and every pair of intersections is joined by a sequence of roads.
Every morning Arman goes to his office, and late at night he gets back home. Nights are very dark and the village roads have no lights, so Arman has started to have trouble finding his way back home. The intersections carry no signs and he cannot tell them apart. His phone has no signal on the way either, so GPS is not possible. To solve the problem he decided to buy a flashlight. Flashlights have different integer beam distances, and a flashlight with a longer beam costs more. A flashlight with range d reveals every intersection within distance at most d of the current intersection. All roads of the village have the same length 1.
When Arman leaves the office towards home, he makes a decision at every intersection of the path he traverses.
Arman does not mind walking a little bit longer as long as he knows that, regardless of his random choices, he will eventually reach home after passing through at most 109 roads. He wants to purchase the cheapest flashlight for that purpose. Find the smallest beam range by which he is able to reach home.
There are multiple test cases in the input. The first line of each test case contains an integer n, the number of intersections in the village (2≤n≤30000). Each of the next n−1 lines contains two integers a and b, meaning that there is a road between intersections a and b (1≤a,b≤n). Arman's home is at intersection 1 and his office is at intersection n. The input terminates with a line containing 0, which should not be processed.
For each test case, output a single line containing the minimum range d of a flashlight that guarantees Arman can always reach home after passing through at most 109 roads, regardless of his random choices. If Arman does not need any flashlight, print 0.