Minimum Nodes
Tag(s):

## Algorithms, Depth First Search, Easy, Graph, Tree

Problem
Editorial
Analytics

You are given a tree with N nodes and each node has some value assigned to it. Now you are given Q tasks of the form X K.
For each task, you have to find the path starting from X such that sum of nodes in the path is at least K and it contains minimum number of nodes. If such path exists, print the count of nodes in the path, else print -1.

Input format

• First line: Two space-separated integers N and Q
• Second line: N space-separated integers (denoting vali)
• Next N -1 lines: Two space-separated integers U and V (denoting an edge between the nodes U and V)
• Next Q lines:Two space-separated integers X and K

Output format

Input Constraints

$1 \le N \le 10^5$
$1 \le Q \le 10$
$1\le val_i \le 10^9$
$1 \le U,V \le N$
$1 \le X \le N$
$1 \le K \le 10^{10}$

SAMPLE INPUT
4 2
2 3 4 5
1 2
2 3
1 4
1 6
2 5

SAMPLE OUTPUT
2
2


Explanation

For task 1: There are two paths from 1 .
1->2->4, sum=9
1->4 , sum=7
So path with minimum number of nodes and sum>=6 is 1->4 as it has only two nodes while the other path has three nodes.
For task 2: Paths with minimum number of nodes and sum>=5 are 2->1 and 2->3. The path 2->1->4 has sum=10 but it has three nodes.

Time Limit: 1.0 sec(s) for each input file.
Memory Limit: 256 MB
Source Limit: 1024 KB
Marking Scheme: Marks are awarded when all the testcases pass.
Allowed Languages: Bash, C, C++, C++14, Clojure, C#, D, Erlang, F#, Go, Groovy, Haskell, Java, Java 8, JavaScript(Rhino), JavaScript(Node.js), Julia, Kotlin, Lisp, Lisp (SBCL), Lua, Objective-C, OCaml, Octave, Pascal, Perl, PHP, Python, Python 3, R(RScript), Racket, Ruby, Rust, Scala, Swift, Swift-4.1, TypeScript, Visual Basic

## CODE EDITOR

Initializing Code Editor...

## This Problem was Asked in

Challenge Name

Equal Experts Hiring Challenge

OTHER PROBLEMS OF THIS CHALLENGE
• Data Structures > Trees
• Data Structures > Advanced Data Structures