Bi-directional roads

4

1 votes
Data Structures, Trees, Lowest Common Ancestor
Problem

There are N cities numbered 1,2,,N and (N1) bi-directional roads in a country. No two cities have multiple roads between them. All roads connect two different cities. For all pairs of cities, there is a path from one to another.

The road between cities uiand vi has cost wi assigned to it which means one has to pay wi unit of money in order to go from city ui to vi or vice-versa. The cost of traveling from one city to another is the sum of costs assigned to the roads that are on the simple path between these cities.

You are given Q queries. For the ith query, you will be provided a set of ki cities {a1,a2,,ak}.

You have to find any city in the country such that the maximum cost from this city to the set of cities is minimum. Formally, let the set of traveling costs from city x to the given set of cities be {d1x,d2x,,dkx}. You are required to find a city x for which max(d1x,d2x,,dkx) is minimum. If there are multiple such cities, print the city with the lowest number.

Input format

  • ​The first line of input contains two integers N the number of cities and Q the number of queries.
  • Next N1 lines contain three integers ui,vi and wi, meaning there is a road connection cities ui and vi which has cost wi assigned to it.
  • Each of the next Q lines has the following format:
    • The ith line starts with a number ki(1ki500) the number of cities in the set, then follows ki cities {a1,a2,,ak}.

Note: Sum of ki over all queries does not exceed 5000.

Output format

For each query, print a single line containing the answer to the query. If there are multiple answers, print the one with the smallest number.

Constraints

1N2×105

1Q5000

1(ui,vi)N

1wi109

ki5000 and 1ki500

1aiN

Time Limit: 5
Memory Limit: 256
Source Limit:
Explanation

For the first query, the cities in the given set are {2,3,5}. 

From city 1, the cost of travelling to cities 2,3 and 5 are 5,8,9 respectively. For 1, we have max(5,8,9)=9.

From city 2,  the cost of travelling to cities 2,3 and 5 are 0,3,14 respectively. For 2, we have max(0,3,14)=14.

From city 3,  the cost of travelling to cities 2,3 and 5 are 3,0,17 respectively. For 3, we have max(3,0,17)=17.

From city 4,  the cost of travelling to cities 2,3 and 5 are 7,10,7 respectively. For 4, we have max(7,10,7)=10.

From city 5,  the cost of travelling to cities 2,3 and 5 are 14,17,0 respectively. For 5, we have max(14,17,0)=17.

So, the answer for the first query will be 1.

Editor Image

?