Journey of the Robber
Time limit4.5sMemory limit1024 MB
Given a tree of N cities ranked by wealth, find for each city the nearest richer city, breaking distance ties by choosing the poorer one.
- Level
Medium7 of 10
- Topics
- Tree, Union-find, Sorting
- Solved
- No attempts yet
Problem
Monopolis is a beautiful and wealthy country. Among its notable features is its layout: cities are connected by roads of equal length, so any two cities can be reached from each other.
Another distinctive feature of Monopolis is that each city has one bank, and no two banks hold the same amount of money. Therefore, each city can be given a distinct number from 1 to that represents its wealth ranking. City 1 has the least money, and city has the most.
Rob is planning a "business trip" to Monopolis. Rob's business is robbing, specifically robbing banks. Rob is an ambitious robber with a strict method: he only targets banks with more money than the one he just robbed. After robbing city , he moves to the closest city with more money than . If several such cities are at the same distance, he chooses the one with the least money. If no city is richer than , he stays in the same city and reflects on his actions.
Rob follows this method strictly, and he asks for your help with his trip. For each city , he wants to know which city he would visit next if his first robbery is in city .
Input
The first line contains an integer (), the number of cities in Monopolis. Each city is identified by a distinct integer from 1 to , in increasing order of wealth.
Each of the next lines contains two integers and (, ), meaning there is a two-way road between cities and . The given roads guarantee a path between every pair of cities.
Output
Print a single line with integers. The -th integer is the next city Rob would visit if his first robbery is in city .