Parcel-delivery app~20 min2s · 256 MBtarget O(log n) time, O(1) spacecomplexity
A parcel depot sorts its parcels in rounds. Each round handles every parcel that is still in play, one handling for each parcel, and pays a fixed setup cost once. After the round, half of the parcels go on to the next round, rounded down. The rounds stop when no parcel is left.
The depot manager wants to plan the shift. You will count the handlings and setups for a given number of parcels, without running every handling.
Write count_handlings(n, setup).
n is the number of parcels at the start, and setup is the cost paid once at the start of every round.setup.n becomes n // 2 (halved and rounded down).Input: n = 10, setup = 0
Output: 18Each row is one round. The round handles every parcel left, then half of them go on, rounded down.
| Round | Parcels left | Handlings in the round | Running total |
|---|---|---|---|
| 1 | 10 | 10 | 10 |
| 2 | 5 | 5 | 15 |
| 3 | 2 | 2 | 17 |
| 4 | 1 | 1 | 18 |
The total is 18 handlings, not 10 × 4 = 40.
Input: n = 13, setup = 4
Output: 39The rounds hold 13, 6, 3 and 1 parcels: 23 handlings. Four rounds pay the setup 4 times: 4 × 4 = 16. The total is 39.
Input: n = 1, setup = 7
Output: 8One round handles one parcel and pays the setup once: 1 + 7 = 8.
0 ≤ n ≤ 1,000,000,000 (parcels)0 ≤ setup ≤ 1,000 (cost paid once for each round)Running one increment for each parcel handled costs about 2 × 10^9 steps at n = 10^9, which is too slow. The number of rounds is only about 30, so a loop over the rounds is fast. The total passes 2 × 10^9, so it needs a 64-bit integer.