Save the Universe
Learn this problemProblem statement
The n universes form a tree rooted at universe 1. Universe i has positive evilness e[i]. For every universe after the root, p gives its parent.
Partition all vertices into vertical branches. Each branch is a non-empty downward path: consecutive vertices in the branch must be connected by a parent-child edge. Every vertex belongs to exactly one branch.
Each branch must contain at most m universes and have total evilness at most k.
Sample partition
1. Original tree
| Level | Left side | Right side |
|---|---|---|
| 0 | Universe 1 · evilness 1 | |
| 1 | Universe 2 · evilness 100 | Universe 3 · evilness 1 |
| 2 | Universe 4 · evilness 1, child of 2 | Universes 5, 6 · evilness 1 each, children of 3 |
2. Cut three edges
Cut
1–2,2–4, and3–5. Keep1–3and3–6, so one downward path remains while the other universes become single-vertex branches.
3. Resulting vertical branches
| Branch | Downward path | Size | Evilness sum |
|---|---|---|---|
| 1 | 1 → 3 → 6 | 3 | 3 |
| 2 | 2 | 1 | 100 |
| 3 | 4 | 1 | 1 |
| 4 | 5 | 1 | 1 |
Every branch has at most m = 3 universes and total evilness at most k = 100, so the minimum answer is 4.
Return the minimum possible number of branches, or -1 if even a single vertex violates the evilness limit.
Function
saveTheUniverse(n: int, m: int, k: long, e: long[], p: int[]) → intExamples
Example 1
n = 6m = 3k = 100e = [1, 100, 1, 1, 1, 1]p = [1, 1, 2, 3, 3]return = 4Universe 2 must form a branch by itself because its evilness already equals k. One optimal partition is [1, 3, 6], [2], [4], and [5].
Constraints
n ≤ 10^5m ≤ 10^5K ≤ 10^18