Under construction

Still being built. Things may change

Tree Tripping

Time limit2sMemory limit1024 MB

Summary
Given a tree and queries that each list k nodes, find the node whose total distance to the listed nodes is smallest and print that sum.
Level

Medium7 of 10

Topics
Tree, Sorting, DFS
Solved
No attempts yet

Problem

A tree with NN nodes is given. Process QQ queries of the following form.

  • k u_1 u_2 ... u_k: Choose any node in the tree. Print the minimum possible sum of distances from the chosen node to nodes u1,u2,…,uku_1, u_2, \dots, u_k.

Input

The first line contains the number of nodes NN and the number of queries QQ, separated by a space. (1≤N≤3000001 \le N \le 300000; 1≤Q≤5000001 \le Q \le 500000)

The next N−1N-1 lines each contain two distinct node numbers aa and bb, separated by a space, which form an edge of the tree. (1≤a,b≤N1 \le a, b \le N)

The next QQ lines each contain a query k u_1 u_2 ... u_k. (1≤k≤N1 \le k \le N; 1≤ui≤N1 \le u_i \le N; i≠ji \ne j implies ui≠uju_i \ne u_j)

The sum of kk over all queries is at most 500000500000.

Output

For each query, print the minimum sum of distances between the chosen node and the given nodes, one per line.

Examples1

  1. Example 1

    Input
    7 4
    1 2
    1 3
    2 4
    2 5
    3 6
    3 7
    1 4
    2 4 5
    2 4 6
    4 4 5 6 7
    
    Expected output
    0
    2
    4
    8