2112 optimal parking-爱代码爱编程
题目描述
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.
输入要求
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 for each test case a line with the minimal distance Michael must walk given optimal parking.
输入样例
2
4
24 13 89 37
6
7 30 41 14 39 42
输出样例
152
70
#include <stdio.h>
int main() {
int t;
scanf("%d", &t);
while (t--) {
int n;
scanf("%d", &n);
int min = 100;
int max = 0;
for (int i = 0; i < n; i++) {
int x;
scanf("%d", &x);
if (x < min) min = x;
if (x > max) max = x;
}
printf("%d\n", (max - min) * 2);
}
return 0;
}
总结:
这段代码中,我们首先输入测试用例数t,然后对每个测试用例进行处理。
对于每个测试用例,我们首先输入商店数量n,然后输入每个商店的位置。在输入过程中,我们记录所有商店位置的最小值和最大值。
根据上面的分析,Michael应该将车停在所有商店位置的中间。因此,他需要走到最左边或最右边的商店(距离为max - min),然后依次访问剩下的商店(距离为max - min),最后回到停车位置(距离为max - min)。所以总共需要走的距离为(max - min) * 2。