Serve interrupts by priority

When several devices ask for attention, the processor serves the most urgent first. In this exercise a handler, once started, always runs to its end.

What to build

A program that works out the order in which interrupts are served, with start and finish times.

Requirements

  • Each interrupt has a name, an arrival time, a priority (a smaller number is more urgent) and a handler duration.
  • The processor is idle at time 0. When it is free, it starts the most urgent interrupt that has already arrived (ties: earlier arrival, then input order). If none has arrived it waits for the next arrival.
  • A handler runs without being interrupted. Print one line for each interrupt in the order served: name start finish.

Input

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

Output

n lines.

Constraints

1 ≤ n ≤ 20; times and durations are whole numbers from 0 to 1000 (durations at least 1).

Example

Input:

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

Output:

A 0 5
B 5 7
C 7 8

Why it works

The interrupt that arrives first is not always served first: while a handler runs, other requests queue up, and when the processor is free the highest priority among them wins.

Examples

Example 1 · Input
3
A 0 3 5
B 1 1 2
C 2 2 1
Expected output
A 0 5
B 5 7
C 7 8
Example 2 · Input
2
disk 10 2 4
timer 0 1 3
Expected output
timer 0 3
disk 10 14

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

Hints

Hint 1

Keep the time t of the processor. When it is free, look at the interrupts with arrival ≤ t that are not served yet.

Hint 2

Pick the smallest priority number; on a tie the earlier arrival, then the earlier one in the input. If none has arrived, jump t to the next arrival time.

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
left = items[:]
while left:
    ready = [x for x in left if x[1] <= t]
    if not ready:
        t = min(x[1] for x in left)
        continue
    pick = min(ready)
    left.remove(pick)
    print(pick[3], t, t + pick[4])
    t += pick[4]

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

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