#K6156. Minimum Trees to Visit

    ID: 31336 Type: Default 1000ms 256MiB

Minimum Trees to Visit

Minimum Trees to Visit

You are given a binary tree where each node has an integer value representing the number of fruits on that tree. Starting from the root, you need to determine the minimum number of trees you must visit so that the sum of the fruits collected is at least a given target value. The visiting order is defined by a breadth-first search (BFS) from the root. If it is not possible to reach the target fruit count by traversing the tree, output -1.

Note: The tree is provided in level order. A token of null represents a missing node. The first line of input is the target number of fruits (an integer). The second line contains the level order traversal of the tree nodes separated by spaces.

Mathematical Formulation: Given a binary tree \(T\) with node values \(a_i\) and a target \(F\), find the minimum integer \(k\) (number of nodes visited in BFS order) such that: \[ \sum_{i=1}^{k} a_i \ge F \] If no such \(k\) exists, output -1.

inputFormat

The input consists of two lines:

  1. The first line contains an integer, the target number of fruits.
  2. The second line contains the level order traversal of the binary tree nodes. Each token is either an integer or the string null (which indicates a missing node). Nodes are separated by spaces.

If the tree is empty, the second line will contain the token null.

outputFormat

Output a single integer which is the minimum number of trees that must be visited (in BFS order) to accumulate at least the target number of fruits. If it is impossible, output -1.

## sample
19
5 3 8 2 4 7 9 1 6
3

</p>