Velma and Queries
Practice
4.3 (7 votes)
Algorithms
Binary search
Depth first search
Easy
Searching
Problem
61% Success 2865 Attempts 30 Points 2s Time Limit 256MB Memory 1024 KB Max Code
The "Mystery Incorporated" once went for an investigation. Since Scooby and Shaggy always create havoc during investigation, Velma decided to give them a question so as to keep them busy.
Velma gave them a tree consisting of N nodes, rooted at node 1 with a number in each node, and asked them several queries. Each query was of the form u l and they had to find the sum of values of all nodes situated at a depth l and were in the subtree of u.
Since Scooby and Shaggy are dumb, they need your help in solving this problem.
Input
The first line will contain the number of test cases T.The first line of each test case will contain two integers N and Q (1 ≤ N, Q ≤ 100,000) - the number of nodes and the number of queries.
The second line of each test case will contain N integers a1, a2, ..., aN, where ai (1 ≤ ai ≤ 10,00,000) is the value stored at the ith node.
The next N-1 lines of each test case will contain two integers u and v, meaning that there is an edge connecting u and v.
The next Q lines contains the queries each of the form u and l.
Output
For each query in every test case, print the answer to the query on a single line.Constraints
- \( 1 \leq T \leq 5, 1 \leq N, Q \leq 1000, \ 1 \leq a_i \leq 10^6 \) in 35% of test cases.
- \( 1 \leq T \leq 10, 1 \leq N, Q \leq 10^5, \ 1 \leq a_i \leq 10^6 \) in 65% of test cases.
Submissions
Please login to view your submissions
Similar Problems
Points:30
16 votes
Tags:
Depth First SearchEasyGraphs
Points:30
8 votes
Tags:
AlgorithmsDepth First SearchGraphs
Points:30
19 votes
Tags:
AlgorithmsDepth First SearchEasyGraphs
Editorial