Engineering platform~30 min2s · 256 MBtarget O(n + total work / turn) time, O(n) spacequeues
A build system runs tasks on one worker in turns. The tasks wait in a line, in the order they were submitted. The worker takes the task at the front and runs it for one turn, or until it is done if it needs less. A task with work left goes to the back of the line.
Each task needs a number of time units of work. The team wants the time at which every task finishes. A build can have 100,000 tasks, with up to 10,000 units each, so acting out every unit of time is too slow.
Write finish_times(work, turn).
work[i] is the number of time units task i needs. It is at least 1. Tasks are in the line in position order.min(turn, work left) units. The clock moves forward by the units used. If the task has work left, it goes to the back of the line.work, at most 10^9, so it fits in an int.Input: work = [5, 2, 7, 3], turn = 3
Output: [13, 5, 17, 11]A queue of task positions acts out the line. Keep the work each task has left.
| Run | Task | Units used | Clock | Work left | What happens |
|---|---|---|---|---|---|
| 1 | 0 | 3 | 3 | 2 | goes to the back |
| 2 | 1 | 2 | 5 | 0 | finishes at 5 |
| 3 | 2 | 3 | 8 | 4 | goes to the back |
| 4 | 3 | 3 | 11 | 0 | finishes at 11 |
| 5 | 0 | 2 | 13 | 0 | finishes at 13 |
| 6 | 2 | 3 | 16 | 1 | goes to the back |
| 7 | 2 | 1 | 17 | 0 | finishes at 17 |
The finish times by task are 13, 5, 17 and 11.
Input: work = [4, 4], turn = 4
Output: [4, 8]A turn as long as every task: the tasks finish in order.
Input: work = [6], turn = 2
Output: [6]One task alone goes round the line three times and finishes at 6.
1 ≤ length of work ≤ 10^5, and 1 ≤ work[i] ≤ 10^41 ≤ turn ≤ 10^4Acting out every unit of time costs the total work, which can be 10^5 × 10^4 = 10^9 units. For the random test in this problem, with 100,000 tasks, that is about 5 × 10^8 steps.
A turn is one queue step, whatever its length. The number of turns is the sum of ceil(work[i] / turn), which is about 551,000 for that test with turn = 1000. The clock reaches 10^9 at most, which fits in an int.