#K92707. Cumulative Books in Category Hierarchy
Cumulative Books in Category Hierarchy
Cumulative Books in Category Hierarchy
You are given a category hierarchy in the form of a tree with (n) categories numbered from 1 to (n). Each category (i) contains a certain number of books denoted by (b_i). The hierarchy is provided as (m) edges (where typically (m = n - 1) for a connected tree) with each edge ((u, v)) indicating that category (v) is a subcategory of category (u).
Your task is to compute the cumulative number of books for specified query categories. The cumulative number of books (S_i) for a category (i) is defined by the formula:
[
S_i = b_i + \sum_{j \in \text{children}(i)} S_j
]
That is, it is the sum of the books in category (i) plus the books in all of its subcategories (and their subcategories recursively).
inputFormat
The input is read from standard input (stdin) and has the following format:
- The first line contains two integers (n) and (q), representing the number of categories and the number of queries, respectively.
- The second line contains (n) integers, where the (i)-th integer denotes the number of books in category (i).
- The third line contains an integer (m) which represents the number of edges in the hierarchy (if (n > 1), then typically (m = n - 1); if (n = 1), then (m = 0)).
- Each of the next (m) lines contains two integers (u) and (v), indicating that category (v) is a subcategory of category (u).
- The final line contains (q) integers, each representing a query category.
outputFormat
For each query, output the cumulative number of books for the queried category on a separate line to standard output (stdout).## sample
5 3
5 3 2 4 1
4
1 2
1 3
2 4
2 5
2 1 4
8
15
4
</p>