The disk arm starts at cylinder h and serves requests by SSTF: each time, the unserved request nearest the head (if two are equally near, the one listed first).
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
The first line has the cylinders in the order they are served, separated by spaces. The second line is total N: the total number of cylinders the head moves.
Examples
Example 1 · Input
53 8 98 183 37 122 14 124 65 67
Expected output
65 67 37 14 98 122 124 183 total 236
Example 2 · Input
50 2 45 55
Expected output
45 55 total 15
Hints
Hint 1
Keep a served[] flag for each request.
Hint 2
Each step, find the unserved request with the smallest abs(request - head); on a tie keep the one listed first.
Hint 3
Add the distance, move the head there, mark it served.
Solution
Show one correct solution (try it yourself first)
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int head, n, request[50], served[50] = {0};
scanf("%d %d", &head, &n);
for (int i = 0; i < n; i++) scanf("%d", &request[i]);
int total = 0;
for (int k = 0; k < n; k++) {
int best = -1;
for (int i = 0; i < n; i++)
if (!served[i] && (best < 0 || abs(request[i] - head) < abs(request[best] - head)))
best = i;
total += abs(request[best] - head);
head = request[best];
served[best] = 1;
printf("%d ", head);
}
printf("\ntotal %d\n", total);
return 0;
}