Given a tree and a set of up to 50 marked nodes per query, find the node minimizing the sum of distances to all marked nodes, for up to 5000 queries.
Hard8TreeDFSPrefix sumLinked listNo attempts yetTime limit2sMemory limit512 MBANTS operates N warehouses numbered 1 to N. A special rail connects exactly two different warehouses. There are exactly N−1 rails, and every warehouse can be reached from every other warehouse, so the rails connect the warehouses as a tree.
From time to time some robots need recalibration. The K affected robots must all gather at a single warehouse, which can be any of the N warehouses. Each robot travels along the shortest path, and every traversal of one rail counts once. The manager picks the gathering warehouse that makes the total count as small as possible.
As a small illustration, take a star where warehouses 2, 3, and 4 each connect to warehouse 1, with one robot at each of 2, 3, and 4. Gathering at warehouse 1 costs 1+1+1=3 rail uses, while gathering at warehouse 2 costs 0+2+2=4. The best gathering point is warehouse 1 with a total of 3.
There are Q queries. Each query gives the locations of the K affected robots, and for each query you must output the smallest achievable total.
The first line holds the number of warehouses, 1≤N≤100,000. Each of the following N−1 lines holds two integers 1≤a,b≤N describing a rail between warehouses a and b. Every warehouse is reachable from every other warehouse. The next line holds the number of queries, 1≤Q≤5000. Each of the next Q lines holds one query: an integer 1≤K≤50 followed by K integers 1≤Ai≤N giving the warehouses of the affected robots. Several robots can share one warehouse.
For each query, output one line with the smallest achievable total number of rail uses.