Ad platform~40 min4s · 256 MBtarget O((n + q) log n) time, O(n) spacesegment-tree
You work on the pacing system of an ad platform. A campaign has a budget, in units, for each hour of the day, and the day can be cut into up to 20,000 slots. The pacing team applies boosts in a ramp: the first hour of the boost gets a extra units, the next hour gets a + d, then a + 2d, and so on.
Between boosts, the team asks for the total budget over a range of hours. Your team lead asks: "Can we answer each question straight away, even after thousands of boosts?" There are up to 20,000 operations.
Write ramp_totals(budgets, ops).
budgets[i] is the budget of hour i, in units.[kind, l, r, a, d].[0, l, r, a, d] is a boost: for every hour i from l to r, add a + d × (i - l) to its budget.[1, l, r, 0, 0] is a question: return the total budget of the hours l to r, both included.Input: budgets = [3, 1, 4, 1], ops = [[0, 0, 3, 2, 1], [1, 1, 2, 0, 0], [0, 2, 3, 1, 0], [1, 0, 3, 0, 0]]
Output: [12, 25]| Operation | Budgets after it | Answer |
|---|---|---|
[0, 0, 3, 2, 1] |
5, 4, 8, 6 (adds 2, 3, 4, 5) | |
[1, 1, 2, 0, 0] |
5, 4, 8, 6 | 4 + 8 = 12 |
[0, 2, 3, 1, 0] |
5, 4, 9, 7 (adds 1, 1) | |
[1, 0, 3, 0, 0] |
5, 4, 9, 7 | 25 |
Input: budgets = [6], ops = [[0, 0, 0, 4, 9], [1, 0, 0, 0, 0]]
Output: [10]A boost over one hour adds only its first amount, 4, so the budget is 10.
Input: budgets = [1, 1, 1, 1], ops = [[0, 0, 3, 5, 0], [1, 1, 2, 0, 0], [1, 0, 3, 0, 0]]
Output: [12, 24]A step of 0 is a flat boost of 5 units for every hour. The budgets become 6, 6, 6, 6.
1 ≤ len(budgets) ≤ 20,0000 ≤ budgets[i] ≤ 1,0001 ≤ len(ops) ≤ 20,000kind is 0 or 1 and 0 ≤ l ≤ r < len(budgets).0 ≤ a ≤ 100 and 0 ≤ d ≤ 10.Touching every hour of a range costs up to 20,000 steps, and 20,000 operations cost 400 million steps. That is too slow. A boost changes a whole range at once, so you cannot update the hours one by one. You need about log n steps for each operation, which is about 15, by tagging whole blocks and fixing their hours later.