Tree in Tree

Time limit6sMemory limit512 MB

Summary
For each vertex subset, count the edges in its minimal connecting subtree using Euler tour order and LCA checks.
Level

Hard8 of 10

Topics
Tree, DFS, Sorting, Binary search
Solved
No attempts yet

Problem

A tree is given. A tree is an undirected and connected graph with nn vertices and n−1n - 1 edges. The vertices are labeled 1,2,…,n1, 2, \ldots, n.

There are qq queries. In each query we choose a subset of the tree's vertices P={v1,v2,…,vk}P = \{v_1, v_2, \ldots, v_k\} and ask how many edges lie in the minimum spanning tree of the set PP. In other words, how many edges belong to at least one path between some vertices of the set PP? Find the answers to all queries.

Input

The first line contains a positive integer nn (2≤n≤1 000 0002 \le n \le 1\,000\,000), the number of the tree's vertices.

Each of the next n−1n - 1 lines contains two distinct positive integers a,ba, b (1≤a,b≤n1 \le a, b \le n) which mean that vertices aa and bb are connected by an edge.

The next line contains a positive integer qq (1≤q≤60 0001 \le q \le 60\,000), the number of queries.

Each of the next qq lines contains first a positive integer kk (k≥2k \ge 2), the size of the set, and then kk distinct positive integers between 11 and nn which are the vertices of the set from the problem statement.

The sum of the sizes kk over all queries is at most 300 000300\,000.

Output

For each query, print the required number of edges on a separate line.

Examples2

  1. Example 1

    Input
    5
    1 2
    2 3
    3 4
    4 5
    4
    2 1 2
    2 3 5
    2 1 5
    3 1 3 5
    
    Expected output
    1
    2
    4
    4
    
  2. Example 2

    Input
    10
    1 2
    2 4
    5 2
    6 3
    3 1
    6 7
    9 7
    8 6
    8 10
    5
    2 4 5
    3 4 5 6
    4 2 4 7 10
    4 4 5 9 10
    9 1 2 3 5 6 7 8 9 10
    
    Expected output
    2
    5
    7
    9
    8