BackhardDynamic Programming

Minimal Vertex Partitioning Solution

Problem Statement

Given a tree with N vertices, each having a weight, determine the optimal partitioning of the tree into subtrees such that the sum of weights of vertices in each subtree does not exceed a given limit. The goal is to minimize the number of subtrees. The tree is represented as an adjacency list where each vertex is associated with a list of its children and a weight.

Example 1
Input
tree = {0: [1, 2], 1: [3, 4], 2: [], 3: [], 4: []}, weights = [10, 5, 5, 3, 2], limit = 15
Output
Infinity

Explanation: Optimal partitioning: subtree {0, 1, 3, 4} with weight sum 10 + 5 + 3 + 2 = 20 is not feasible, so partition into {0, 2} with weight sum 10 + 5 = 15 and {1, 3, 4} with weight sum 5 + 3 + 2 = 10.

Example 2
Input
tree = {0: [1], 1: [2, 3], 2: [], 3: []}, weights = [8, 9, 7, 6], limit = 14
Output
Infinity

Explanation: Optimal partitioning: since the sum of weights of any two vertices exceeds the limit, each vertex must be in its own subtree, resulting in 4 subtrees, but since vertex 0 can include vertex 2 or 3, we get 3 subtrees.

Constraints

  • 2 <= N <= 100
  • 1 <= limit <= 1000
  • 1 <= weights[i] <= 1000
  • The tree is represented as an adjacency list and is connected
Live Compiler
Loading...
Test Cases & Output
🔒 Sign up to run your code

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free