Grasshopper Route
Time limit1sMemory limit512 MB
Given a tree and two vertices s and t, construct the specific valid Grasshopper route defined by a recursive rule on the path components.
- Level
Medium7 of 10
- Topics
- Tree, DFS, Recursion, Implementation
- Solved
- No attempts yet
Problem
A grasshopper is exploring a tree. A tree is an undirected graph in which every two vertices are joined by exactly one path. A grasshopper standing on a vertex can jump to another vertex only if the distance between the two vertices is at most , where the distance is the number of edges on the path that joins them. The grasshopper wants to visit every vertex of the tree exactly once, starting at the vertex it stands on and finishing at the vertex it has chosen.
You are given a tree with vertices and two vertices and . A grasshopper route for and is an ordering of all vertices of the tree such that , , and the grasshopper can jump from to for every in . Every pair of vertices of a tree is joined by a grasshopper route, which was proved in 1960.
In the tree drawn below, is a grasshopper route for and . The grasshopper can jump from vertex to vertex because the distance between them is , but it cannot jump from vertex to vertex . A tree can have more than one grasshopper route, so the output section fixes one of them.

The figure shows one grasshopper route from to .
Input
The first line contains an integer , the number of vertices of the tree (). Each of the next lines contains two integers and that describe an edge between vertex and vertex . The vertices are numbered from to . The last line contains two distinct integers and , the start vertex and the end vertex of the route.
Output
A tree can have many grasshopper routes, so print the one that the rule below picks. Print the vertices the grasshopper passes through in lines, one vertex per line, in order.
- Let be the unique path from to in the tree.
- Delete the edges of that path. The tree falls apart into components. Call the component that contains , and root at .
- For a vertex of a rooted tree, define the sequence as follows. If has no child, is the one term sequence . Otherwise let be the children of in increasing order of vertex number, and let be , followed by written backwards, then written backwards, and so on up to written backwards.
- The answer is concatenated in this order, followed by written backwards. Each is computed inside the component .
This ordering is always a grasshopper route.