Maps app~25 min2s · 256 MBtarget O(q log n) time, O(1) spacerecursion
A maps app draws a region of m tiles with a recursive function. A call on at most cutoff tiles draws them one by one, and each tile is compared with every other, so the work is m × m.
A larger call spends m units of work on splitting the region and merging the pictures. Then it calls itself on parts smaller regions. The tiles are shared out as evenly as possible, so the sizes can differ by one. Before a release, the team wants the total work of a region.
Write split_work(sizes, parts, cutoff).
m tiles is m × m when m <= cutoff. This includes m = 0, which is 0.m plus the work of parts calls. Let q = m // parts and r = m % parts. The first r calls get q + 1 tiles each, and the other parts - r calls get q tiles each.n in sizes, return the total work of the call on n tiles, counting every call below it.Input: sizes = [10], parts = 3, cutoff = 2
Output: [32]Take n = 10, parts = 3 and cutoff = 2. Group the calls of each level by size.
| Level | Calls by size | Work of the level |
|---|---|---|
| 1 | one call of 10 | 10 |
| 2 | one call of 4, two calls of 3 | 4 + 3 × 2 = 10 |
| 3 | one call of 2, eight calls of 1 | 2 × 2 + 8 × 1 = 12 |
The call on 10 tiles splits into 4, 3 and 3. The call on 4 splits into 2, 1 and 1, and each call on 3 splits into 1, 1 and 1. The calls on 2 and 1 are at the cutoff. The total is 10 + 10 + 12 = 32.
Input: sizes = [1, 2], parts = 2, cutoff = 1
Output: [1, 4]The call on 1 tile is at the cutoff, so it does 1 unit. The call on 2 tiles is above the cutoff. It does 2 units, then splits into two calls of 1, which do 1 unit each. The totals are 1 and 4.
Input: sizes = [100, 1000], parts = 2, cutoff = 10
Output: [1028, 14832]With two parts and a cutoff of 10, a region of 100 tiles costs 1,028 units and a region of 1,000 tiles costs 14,832 units.
1 ≤ sizes.length ≤ 1,0001 ≤ sizes[i] ≤ 1,000,000,0002 ≤ parts ≤ 41 ≤ cutoff ≤ 1,000A region of 10^9 tiles with two parts and cutoff 1 has about 2 × 10^9 calls, so the tree cannot be run. But the tree is regular. Every call on a level is one of at most two neighbouring sizes, so a level can be described by two numbers and their counts.