FCFS disk scheduling

The simplest disk scheduler serves requests in the order they arrive (FCFS). It is fair, but the arm may zigzag across the disk.

What to build

Serve disk requests first come, first served and print the total head movement.

Requirements

  • The head starts at cylinder h. Serve the requests in the order given; each one moves the head by the distance to that cylinder.
  • Print total N, the total distance moved, and average A, the total divided by the number of requests, with 2 decimal places.

Input

The first line has h and n (0 ≤ h ≤ 9999, 1 ≤ n ≤ 50). The second line has the n requested cylinders (0 to 9999).

Output

Two lines: total N and average A.

Constraints

n is never a multiple of 8 in the tests, so no average ends in an exact tie when rounded.

Example

Input:

53 8
98 183 37 122 14 124 65 67

Output:

total 640
average 80.00

Why it works

Total movement is the sum of the distances between neighbours in the sequence head, request 1, request 2, and so on. FCFS never reorders anything, so the sum is whatever the arrival order makes it. Other schedulers get a smaller sum by reordering.

Examples

Example 1 · Input
53 8
98 183 37 122 14 124 65 67
Expected output
total 640
average 80.00
Example 2 · Input
10 3
10 20 10
Expected output
total 20
average 6.67

Hints

Hint 1

Keep the head position and a total. For each request add the absolute difference from the head, then move the head there.

Hint 2

abs() is in stdlib.h.

Hint 3

Average = total / n as doubles, printed with %.2f.

Solution

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

int main(void) {
    int h, n, r, total = 0;
    scanf("%d %d", &h, &n);
    for (int i = 0; i < n; i++) {
        scanf("%d", &r);
        total += abs(r - h);
        h = r;
    }
    printf("total %d\n", total);
    printf("average %.2f\n", (double)total / n);
    return 0;
}

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

Lesson: Disks and disk scheduling →