Ride-hailing app~35 min2s · 256 MBtarget O((n + q) log n) time, O(n) spacesegment-tree
You work on a ride-hailing app. A pickup zone keeps, for each minute of the day, how many riders asked for a ride in that minute. Riders change their requests, so a single minute's count can be replaced.
Dispatch wants to know how long people would wait if a fleet collected everyone at the end of a chosen minute. A rider who asked in minute i and is collected at the end of minute b has waited b - i + 1 minutes. The zone has up to 50,000 minutes and 50,000 operations.
Write pickup_waits(counts, ops).
counts[i] is the number of riders who asked for a ride in minute i.[kind, a, b].[0, a, b] replaces counts[a] with b.[1, a, b] is a question about the riders who asked in the minutes a to b, both included. It asks for the total number of minutes they wait if all of them are collected at the end of minute b.Input: counts = [2, 0, 3, 1], ops = [[1, 0, 3], [0, 1, 4], [1, 1, 3]]
Output: [15, 19]| Operation | Counts in the range | Minutes waited | Total |
|---|---|---|---|
[1, 0, 3] |
2, 0, 3, 1 | 4, 3, 2, 1 | 2 × 4 + 0 × 3 + 3 × 2 + 1 × 1 = 15 |
[0, 1, 4] |
minute 1 becomes 4 | ||
[1, 1, 3] |
4, 3, 1 | 3, 2, 1 | 4 × 3 + 3 × 2 + 1 × 1 = 19 |
Input: counts = [5], ops = [[1, 0, 0]]
Output: [5]Five riders asked in minute 0 and are collected at the end of minute 0. Each waits 1 minute.
Input: counts = [1, 1, 1, 1, 1], ops = [[0, 4, 10], [1, 2, 4], [1, 0, 4]]
Output: [15, 24]After the change the counts are 1, 1, 1, 1, 10. Minutes 2 to 4 wait 3, 2 and 1 minutes: 3 + 2 + 10 = 15. Minutes 0 to 4 wait 5, 4, 3, 2 and 1 minutes: 5 + 4 + 3 + 2 + 10 = 24.
1 ≤ len(counts) ≤ 50,0000 ≤ counts[i] ≤ 100,0001 ≤ len(ops) ≤ 50,000kind is 0 or 1 and 0 ≤ a ≤ b < len(counts) for a question. For a change, 0 ≤ a < len(counts) and 0 ≤ b ≤ 100,000.Walking over a whole range for each question costs up to 50,000 steps, and 50,000 questions cost 2.5 billion steps. That is too slow for two seconds. You need about log n steps for a question and for a change, which is about 16. The answer for one question can reach about 1.25 × 10^14, so 32-bit numbers are not enough.