Nested interrupts

Now a more urgent interrupt may interrupt a handler that is already running. The interrupted handler goes on later, from where it stopped.

What to build

A program that simulates the processor with preemptive priority interrupts and prints when each interrupt finishes.

Requirements

  • Each interrupt has a name, an arrival time, a priority (smaller is more urgent) and a duration in time units.
  • At every time unit the processor runs the most urgent interrupt that has arrived and is not finished (ties: earlier arrival, then input order). An interrupt that was cut off continues later with the time it still needs.
  • Print name finish for each interrupt, in the order in which they finish.

Input

A line with n, then n lines name arrival priority duration.

Output

n lines.

Constraints

1 ≤ n ≤ 20; arrivals from 0 to 100; durations from 1 to 50.

Example

Input:

3
A 0 3 5
B 1 1 2
C 2 2 1

Output:

B 3
C 4
A 8

Why it works

Whenever a more urgent request arrives, the processor saves the state of the running handler and switches, so urgent work is never delayed by less urgent work, at the price of the longer finish time of the interrupted handler.

Examples

Example 1 · Input
3
A 0 3 5
B 1 1 2
C 2 2 1
Expected output
B 3
C 4
A 8
Example 2 · Input
2
low 0 5 4
high 10 1 2
Expected output
low 4
high 12

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Simulate one time unit at a time. At time t, among the interrupts with arrival ≤ t and time left, run the one with the smallest priority number (ties: earlier arrival, then input order) for one unit.

Hint 2

Record the time when an interrupt's last unit ends as its finish time. If no interrupt is ready, simply move to the next time unit.

Solution

Show one correct solution (try it yourself first)
n = int(input())
items = []
for i in range(n):
    name, a, p, d = input().split()
    items.append([int(p), int(a), i, name, int(d)])
t = 0
done = []
left = items[:]
while left:
    ready = [x for x in left if x[1] <= t]
    if ready:
        x = min(ready)
        x[4] -= 1
        if x[4] == 0:
            left.remove(x)
            done.append((x[3], t + 1))
    t += 1
for name, f in done:
    print(name, f)

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Input and output: polling, interrupts and DMA →