原文:
Problem Description
When shopping on Long Street, Michael usually parks his car at some random location, and then walks to the stores he needs.
Can you help Michael choose a place to park which minimises the distance he needs to walk on his shopping round?
Long Street is a straight line, where all positions are integer.
You pay for parking in a specific slot, which is an integer position on Long Street. Michael does not want to pay for more than one parking though. He is very strong, and does not mind carrying all the bags around.
Input
The first line of input gives the number of test cases, 1 <= t <= 100. There are two lines for each test case. The first gives the number of stores Michael wants to visit, 1 <= n <= 20, and the second gives their n integer positions on Long Street, 0 <= xi <= 99.
Output
Output for each test case a line with the minimal distance Michael must walk given optimal parking.
Sample Input
2
4
24 13 89 37
6
7 30 41 14 39 42
Sample Output
152
70
題意理解:
這道題原文有一點(diǎn)坑斥废,開始時(shí)不一定能讀懂,但讀懂以后就會(huì)覺(jué)得特別簡(jiǎn)單给郊。
題意大致如下:
有n個(gè)地點(diǎn)牡肉,每個(gè)地點(diǎn)的位置都在同一條直道上望抽,有個(gè)人把車停在某一個(gè)地點(diǎn)玉转,然后他去那條直道上所有的n個(gè)點(diǎn)購(gòu)物,最后回到停車的地點(diǎn)队寇。問(wèn)在最佳停車點(diǎn)的情況下那個(gè)人需要步行的最小距離吩屹。
事實(shí)上跪另,如果你把線段圖畫出來(lái)的話,你就會(huì)發(fā)現(xiàn):不管怎樣煤搜,最小的距離就是最大距離點(diǎn)和最小距離點(diǎn)的值之差再乘以2.
參考代碼如下:
#include <iostream>
#include <string>
using namespace std;
int position[22];
int min_d(int *p,int n) {
int max = *p,min = *p;
int distance;
int *pi;
for (pi = p;pi < p+n;pi++) {
if (*pi > max) {
max = *pi;
}
else if (*pi < min) {
min = *pi;
}
}
distance = (max - min) * 2;
return distance;
}
int main() {
int t;
int n;
int distance;
cin >> t;
while (t--) {
cin >> n;
memset(position,0,sizeof(position));
for (int i = 0;i < n;i++) {
cin >> position[i];
}
distance = min_d(position,n);
cout << distance << endl;
}
return 0;
}
如果你對(duì)我的博客有什么建議的免绿,歡迎交流。