#K77667. Subtree Sum Queries

    ID: 34916 Type: Default 1000ms 256MiB

Subtree Sum Queries

Subtree Sum Queries

Given a tree with n nodes and n-1 edges defining its structure, where each node's value is equal to its label, your task is to compute the sum of the node values in the subtree rooted at each queried node. The tree is rooted at node 1. A subtree of a node includes the node itself and all of its descendants.

Mathematical Formulation:

For a tree with nodes labeled from 1 to n and for a query node u, compute \[ S(u)= u + \sum_{v \in \text{subtree}(u) \setminus \{u\}} v \]

Constraints:

  • 1 \(\leq\) n \(\leq\) 105
  • 1 \(\leq\) query node \(\leq\) n

inputFormat

The input is given via stdin in the following format:

  1. An integer n representing the number of nodes.
  2. n-1 lines, each containing two integers u and v denoting an edge between the nodes u and v.
  3. An integer q representing the number of queries.
  4. A single line with q space-separated integers, each representing a query node.

outputFormat

Output to stdout a single line containing q space-separated integers. Each integer is the sum of the values in the subtree rooted at the corresponding query node.

## sample
7
1 2
1 3
2 4
2 5
3 6
3 7
3
2 3 1
11 16 28