Round robin from time zero

Round robin gives each process a turn of at most q time units, in a circle. When every process arrives at time 0, the queue is just P1, P2, ..., Pn, round after round.

What to build

Run round robin when all processes arrive at time 0, and print each process's completion time.

Requirements

  • The processes P1, P2, ..., Pn are in the queue in that order. A process runs for q units, or less if it needs less. If it still has time left it goes to the back of the queue.
  • Print Pi CT for each process in order P1, P2, ..., where CT is the time at which it finishes.

Input

The first line has n and q (1 ≤ n ≤ 20, 1 ≤ q ≤ 10). The second line has the n burst times (1 to 50).

Output

n lines Pi CT.

Constraints

Nothing arrives later than time 0, so the CPU is never idle before the last process finishes.

Example

Input:

3 4
24 3 3

Output:

P1 30
P2 7
P3 10

Why it works

Going round the array again and again is the same as a circular queue when nobody arrives later: the process that was stopped goes behind everyone else, which is exactly the next position in the cycle. The completion time is the clock at the moment the last unit has run.

Examples

Example 1 · Input
3 4
24 3 3
Expected output
P1 30
P2 7
P3 10
Example 2 · Input
4 2
5 3 1 2
Expected output
P1 11
P2 10
P3 5
P4 7

Hints

Hint 1

Keep a clock and the time left for each process. Go round the processes P1 to Pn again and again.

Hint 2

A process with time left runs for min(q, left). Add that to the clock; if it reaches zero, the clock is its completion time.

Hint 3

Stop when every process is done. Skip processes that are already finished.

Solution

Show one correct solution (try it yourself first)
#include <stdio.h>

int main(void) {
    int n, q, burst[20], left[20], finish[20];
    scanf("%d %d", &n, &q);
    for (int i = 0; i < n; i++) {
        scanf("%d", &burst[i]);
        left[i] = burst[i];
        finish[i] = 0;
    }
    int time = 0, done = 0;
    while (done < n) {
        for (int i = 0; i < n; i++) {
            if (left[i] == 0) continue;
            int run = left[i] < q ? left[i] : q;
            time += run;
            left[i] -= run;
            if (left[i] == 0) {
                finish[i] = time;
                done++;
            }
        }
    }
    for (int i = 0; i < n; i++) printf("P%d %d\n", i + 1, finish[i]);
    return 0;
}

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

Lesson: Round robin, SRTF and priority →