Tree and Queries
Time limit3sMemory limit1024 MB
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 vertices numbered from 1 to is given. The -th edge connects two distinct vertices and . ()
Choose some of the vertices, and let the chosen vertices be . If there is an () with , then vertex is said to belong to .
For two distinct vertices and that belong to , say that " and are connected on " if you can move between and along the tree using only vertices that belong to .
For example, consider the tree below. ()

If and , then " and ", " and ", and " and " are each connected on . However, " and " and " and " are not connected on .
Count the vertex pairs that satisfy all of the following conditions. This count is the connection strength of .
- and are two distinct vertices.
- .
- and are connected on .
Given a chosen set , write a program that computes the connection strength of . You must answer such queries.
Input
The first line contains an integer .
Each of the next lines contains two integers and , describing the -th edge.
The next line contains an integer .
Each of the next lines describes a query: an integer , followed by integers .
Output
For each query, print the connection strength of the given on its own line, in order.
Constraints
- For every (), .
- For every (), .
- For every (), .
- The given graph is a tree.
- For every query, .
- In each query, for every (), .
- In each query, the chosen vertices are distinct.
- The sum of over all queries is at most .