Distance between cities

1.6

5 votes
Data Structures, Lowest Common Ancestor, Trees, LCA
Problem

A country consists of N cities that are represented as a tree graph. A tree graph is an undirected acyclic graph.

The leaders of the country decided to hold Q meetings. For the ith meeting, there are Ki leaders in different cities. For each meeting, the leaders want to find a city such that the maximum distance between any of the Ki cities and a selected city is minimum.

Note: This city does not have to be a part of the Ki cities.

Your task is to determine the minimum of the maximum distances obtained between the Ki cities and the selected city.

Input format

  • First line: Two space-separated integers N and Q
  • Next N1 lines: Two space-separated integers u and v denoting an edge between u and v
  • Next 2×Q lines:
    • First line: Ki denoting the number of nodes in the query
    • Second line: Ki space-separated integers where Xi is denoting the cities of this query

Output format

Print Q lines, each line contains the value that represents the minimum of the maximum distance between all the Ki cities and the city selected.

Constraints

1N,Q3×1051u,vN1XiNQi=1KiN

Time Limit: 2
Memory Limit: 256
Source Limit:
Explanation

Queries as in order:

  1. The best city to choose is city 3
  2. The best city to choose is city 2
  3. The best city to choose is city 1
  4. The best city to choose is city 3
  5. The best city to choose is city 1

Here is a picture of the tree for further clarity:

Editor Image

?