Under construction

Still being built. Things may change

Tree and Queries

Time limit3sMemory limit1024 MB

Summary
For each query, count the pairs of chosen vertices whose tree path uses only chosen vertices, given a tree with up to 250,000 vertices.
Level

Medium6 of 10

Topics
Tree, Sorting, Implementation
Solved
No attempts yet

Problem

A tree with NN vertices numbered from 1 to NN is given. The ii-th edge connects two distinct vertices AiA_i and BiB_i. (1≤i≤N−11 \le i \le N-1)

Choose some of the NN vertices, and let the chosen vertices be S={s1,s2,…,sK}S = \{s_1, s_2, \dots, s_K\}. If there is an ii (1≤i≤K1 \le i \le K) with si=vs_i = v, then vertex vv is said to belong to SS.

For two distinct vertices uu and vv that belong to SS, say that "uu and vv are connected on SS" if you can move between uu and vv along the tree using only vertices that belong to SS.

For example, consider the tree below. (N=7N = 7)

If K=6K = 6 and S={1,2,3,4,5,6}S = \{1, 2, 3, 4, 5, 6\}, then "11 and 22", "33 and 55", and "44 and 66" are each connected on SS. However, "11 and 66" and "22 and 77" are not connected on SS.

Count the vertex pairs (u,v)(u, v) that satisfy all of the following conditions. This count is the connection strength of SS.

  1. uu and vv are two distinct vertices.
  2. 1≤u<v≤N1 \le u < v \le N.
  3. uu and vv are connected on SS.

Given a chosen set SS, write a program that computes the connection strength of SS. You must answer QQ such queries.

Input

The first line contains an integer NN.

Each of the next N−1N-1 lines contains two integers AiA_i and BiB_i, describing the ii-th edge.

The next line contains an integer QQ.

Each of the next QQ lines describes a query: an integer KK, followed by KK integers s1,…,sKs_1, \dots, s_K.

Output

For each query, print the connection strength of the given SS on its own line, in order.

Constraints

  • 2≤N≤250 0002 \le N \le 250\,000
  • 1≤Q≤100 0001 \le Q \le 100\,000
  • For every ii (1≤i≤N−11 \le i \le N-1), 1≤Ai≤N1 \le A_i \le N.
  • For every ii (1≤i≤N−11 \le i \le N-1), 1≤Bi≤N1 \le B_i \le N.
  • For every ii (1≤i≤N−11 \le i \le N-1), Ai≠BiA_i \ne B_i.
  • The given graph is a tree.
  • For every query, 1≤K≤N1 \le K \le N.
  • In each query, for every ii (1≤i≤K1 \le i \le K), 1≤si≤N1 \le s_i \le N.
  • In each query, the KK chosen vertices s1,…,sKs_1, \dots, s_K are distinct.
  • The sum of KK over all QQ queries is at most 1 000 0001\,000\,000.

Examples1

  1. Example 1

    Input
    7
    1 2
    1 3
    1 5
    2 7
    4 6
    4 7
    6
    1 1
    2 1 2
    4 1 2 3 4
    5 1 2 4 6 7
    6 1 2 3 4 5 6
    7 1 2 3 4 5 6 7
    
    Expected output
    0
    1
    3
    10
    7
    21