Key Sum Management
Learn this problemProblem statement
Key 1 is the root of an initial tree with n keys. Every key starts with value 0, and a key's level is its distance from the root.
The first n - 1 rows of operations contain the two endpoints of the initial tree edges. The remaining q rows are operations:
Ro p v: add a new keyvas a child ofp. Its value starts at0, andvis the current node count plus one.Re level z: for every keyucurrently at that exact level, letxbeu's value immediately before this operation. Assignx + ztouand every key currently inu's subtree.
How the tree changes
1. Initial tree
| Level | Left subtree | Middle | Right subtree |
|---|---|---|---|
| 0 | Key 1 · value X1 | ||
| 1 | Key 2 · X2 | — | Key 3 · X3 |
| 2 | Key 4 · X4, Key 5 · X5 | — | Key 6 · X6, Key 7 · X7 |
| 3 | Key 8 · X8 under key 4 | — | — |
2. Rotation
Ro 1 9adds key9as a new child of key1. Its value starts at0; every existing edge and value stays unchanged.
| Level | Left subtree | New middle key | Right subtree |
|---|---|---|---|
| 0 | Key 1 · value X1 | ||
| 1 | Key 2 · X2 | Key 9 · 0 | Key 3 · X3 |
| 2 | Keys 4, 5 · unchanged | — | Keys 6, 7 · unchanged |
| 3 | Key 8 · unchanged | — | — |
3. Rekey
Re 1 4starts at every level-1key. Each selected key's previous value plus4is copied through its whole subtree.
| Level | Key 2 subtree | Key 9 subtree | Key 3 subtree |
|---|---|---|---|
| 0 | Key 1 stays X1 | ||
| 1 | Key 2 · X2 + 4 | Key 9 · 4 | Key 3 · X3 + 4 |
| 2 | Keys 4, 5 · X2 + 4 | — | Keys 6, 7 · X3 + 4 |
| 3 | Key 8 · X2 + 4 | — | — |
Return the sum of all key values after all operations.
Function
keySumManagement(operations: String[][], n: int, q: int) → longExamples
Example 1
operations = [["1", "2"], ["2", "4"], ["1", "3"], ["4", "5"], ["Re", "1", "10"], ["Ro", "4", "6"], ["Re", "2", "4"], ["Re", "3", "4"]]n = 5q = 4return = 70The final values of keys 1 through 6 are [0, 10, 10, 14, 18, 18], whose sum is 70.
Example 2
operations = [["2", "1"], ["3", "1"], ["4", "2"], ["5", "1"], ["Ro", "4", "6"], ["Re", "2", "91277"], ["Re", "1", "50944"], ["Ro", "1", "7"], ["Re", "1", "17666"]]n = 5q = 5return = 360716After the final Rekey operation, keys 2 through 6 each have value 68610, key 7 has value 17666, and key 1 remains 0. Their sum is 360716.