Distance between cities
Practice
1.6 (5 votes)
Data structures
Lowest common ancestor
Trees
Lca
Problem
85% Success 1374 Attempts 50 Points 2s Time Limit 256MB Memory 1024 KB Max Code

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 \(i^{th}\) meeting, there are \(K_i\) leaders in different cities. For each meeting, the leaders want to find a city such that the maximum distance between any of the \(K_i\) cities and a selected city is minimum.

Note: This city does not have to be a part of the \(K_i\) cities.

Your task is to determine the minimum of the maximum distances obtained between the \(K_i\) cities and the selected city.

Input format

  • First line: Two space-separated integers \(N\) and \(Q\)
  • Next \(N-1\) lines: Two space-separated integers \(u\) and \(v\) denoting an edge between \(u\) and \(v\)
  • Next \(2 \times Q\) lines:
    • First line: \(K_i\) denoting the number of nodes in the query
    • Second line: \(K_i\) space-separated integers where \(X_i\) 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 \(K_i\) cities and the city selected.

Constraints

\(1 \leq N,Q \leq 3 \times 10^5\\ 1 \leq u, v \leq N\\ 1 \leq X_i \leq N\\ \sum_{i=1}^{Q} K_i \leq N\)

Please login to use the editor

You need to be logged in to access the code editor

Loading...

Please wait while we load the editor

Loading...
Results
Custom Input
Run your code to see the output
Submissions
Please login to view your submissions
Similar Problems
Points:50
1 votes
Tags:
Dynamic ProgrammingData StructuresTreesLowest Common Ancestor
Points:50
2 votes
Tags:
TreesBinary SearchData StructuresLowest Common AncestorSparse table
Points:50
1 votes
Tags:
LoopsData StructuresCentroid decompositionTreeMedium-Hard