hdoj1673

原文:

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;
}

如果你对我的博客有什么建议的,欢迎交流。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,559评论 0 23
  • 在某群看到一张几个孩子站成一排的照片,没做作业,老师要求家长各自认领,瞬间一股复杂的情绪冒出来,各种悲伤、...
    志在从容中道阅读 3,633评论 0 3
  • 长大的牧童 拍着老黄牛 真辛苦你了
    长马阅读 775评论 0 2
  • 不以物喜,不以已悲,不以情欢,不以离苦。值此人生之境,无为而无不为,无思而无不思,无欲而无不欲,无求而无不求。这时...
    花语_21b1阅读 1,472评论 0 0
  • 又逢一岁秋光漾, 翠叶流金果错纷。 千架龙珠由客采, 浅红深紫惜无君。
    A_master阅读 1,274评论 0 3

友情链接更多精彩内容