原文:
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
题意理解:
这道题原文有一点坑,开始时不一定能读懂,但读懂以后就会觉得特别简单。
题意大致如下:
有n个地点,每个地点的位置都在同一条直道上,有个人把车停在某一个地点,然后他去那条直道上所有的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;
}
如果你对我的博客有什么建议的,欢迎交流。