Roads in a city

5

7 votes
Loops, Data Structures, Medium, Tree
Problem

The layout of a city is in the form of a tree. There are N1 roads connecting N houses and every pair of houses has exactly one unique path between them. The distance between the two houses is equal to the number of roads in this unique path.

On the ith day, a member of the (Pi)th house joins a company (1i, PiN). A meeting of the members is held every day, and everyone, who is a member of the company until that day, is supposed to join. The meeting point is decided such that the maximum distance travelled by any of the members is as small as possible.

Your task is to help them decide the meeting point on each of the N days. If multiple locations are equally convenient, then select the one that has the lowest index.

Input format

  • First line: A single integer N that denotes the number of houses in your city
  • Next N1 lines: Two space-separated integers u,v, that represents a bidirectional road connecting the houses u and v
  • Last line: N space-separated integers that denote the array P. The ith integer of this array denotes that the (Pi)th house joined the company on the ith day.

Output format

Print the N space-separated integers in a single line. The ith integer represents the meeting point for the meeting that has to be held on the ith day by satisfying all the conditions that are mentioned in the problem statement.

Constraints

1N2105

1u,vN

It is guaranteed that the road network will form a valid tree.

1PiN. All the Pi's are pair-wise distinct.

For 20% of the test files, 1N1000

                 

Time Limit: 1
Memory Limit: 256
Source Limit:
Explanation

On day 1, only {3} is a part of the company. The ideal meetup point is, therefore, 3.

On day 2, the company consists of {2,3}. Both the locations are equally suitable for being the meetup point (Maximum distance travelled is 1). So we choose the one with the lower index, i.e. 2.

On day 3, the company consists of {1,2,3}.  3 is the only ideal meetup location, since the maximum distance travelled by any of the members is 1. (If 1 or 2 would have been chosen, the maximum distance would have been 2).

On day 4, everyone is a part of the company. 1 and 3 are both ideal locations (maximum distance travelled by any of the members is 2). We choose the one with the lower index, i.e 1.

Editor Image

?