Monitoring~40 min2s · 256 MBtarget O((n + q) log n) time, O(n) spacefenwick-tree · tree-recursion
A monitoring team keeps its services in a tree. Service 0 is the top, and parents[v] is the service that owns service v. Each service has an error count, values[v] at the start.
Two kinds of events arrive in order. An add changes the error count of one service by a signed amount. A total asks for the sum of the error counts of a service and every service below it. The team answers each total at once.
Write subtree_totals(parents, values, ops).
parents.length services, numbered from 0. parents[0] is -1, and every other entry is the id of the owner of that service.values[v] is the starting error count of service v.ops[i] is [1, v, x] to add x to the count of service v, or [2, v, 0] to ask for the total of the subtree of v.Input: parents = [-1, 0, 0, 1, 1, 2, 2, 3], values = [5, 3, 8, 2, 6, 1, 4, 7], ops = [[2,1,0],[1,3,5],[2,1,0],[1,4,-6],[2,0,0],[2,2,0],[2,7,0]]
Output: [18, 23, 35, 13, 7]Services 1 and 2 report to 0, services 3 and 4 report to 1, services 5 and 6 report to 2, and service 7 reports to 3. The subtree of service 1 holds services 1, 3, 4 and 7, with 3 + 2 + 6 + 7 = 18 errors.
The solution walks the tree and numbers the services by the order the walk reaches them. A subtree is then one unbroken stretch of positions. A Fenwick tree over the positions adds a change at one position and totals a stretch as the difference of two prefix sums.
| Service | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|---|
| First position (tin) | 0 | 1 | 5 | 2 | 4 | 6 | 7 | 3 |
| Last position in the subtree (tout) | 7 | 4 | 7 | 3 | 4 | 6 | 7 | 3 |
The walk order is services 0, 1, 3, 7, 4, 2, 5, 6, with starting counts 5, 3, 2, 7, 6, 8, 1, 4. The first total is the prefix sum up to position 4, which is 23, minus the prefix sum before position 1, which is 5. That gives 18. Adding 5 to service 3 raises the next total of service 1 to 23.
Input: parents = [-1], values = [9], ops = [[2,0,0],[1,0,-4],[2,0,0]]
Output: [9, 5]A single service is its own subtree.
Input: parents = [-1, 0, 1], values = [1, 2, 3], ops = [[2,0,0],[2,1,0],[2,2,0],[1,2,10],[2,0,0],[2,1,0]]
Output: [6, 5, 3, 16, 15]A change at the bottom of the chain appears in every total above it.
1 ≤ parents.length ≤ 100,000, parents[0] = -1, and every other entry is a valid service that makes the services a tree rooted at 0values.length = parents.length, and 0 ≤ values[v] ≤ 10^91 ≤ ops.length ≤ 100,000; each add is [1, v, x] with -10^9 ≤ x ≤ 10^9, each total is [2, v, 0], and 0 ≤ v < parents.lengthWalking the subtree for each total costs up to n steps, and 100,000 totals on a deep tree cost about 10^10. Keeping every subtree total up to date costs up to the depth for each add. A Fenwick tree over a walk order costs about 17 steps for each operation, about 2 × 10^6 steps in all. Totals can pass 10^14, so they need 64-bit integers.