第一行给出柱面号的个数n,第二行给出磁头的起始位置,第三行给出n个柱面号
8 53 98 183 37 122 14 124 65 67
#include<iostream> #include<algorithm> using namespace std; const int N = 100; int queue[N],index;//index记录磁头起始位置在queue里的下标 int main() { int n, start, sum = 0;//分别记录柱面号的个数,磁头初始位置和磁头共移动了多少个磁道 cin >> n >> start; queue[0] = start; for (int i = 1; i < n+1; i++) cin >> queue[i]; sort(queue, queue + n + 1); for (int i = 0; i < n + 1; i++)//初始化index if (queue[i] == start) { index = i; break; } for (int i = index-1; i >=0; i--) { int temp = start - queue[i]; sum += temp; start = queue[i]; } sum += queue[index] + queue[0] * 2; start = queue[index + 1]; for (int i = index + 2; i < n+1; i++) { int temp = queue[i] - start; sum += temp; start = queue[i]; } cout << sum; return 0; }