HDU 2083 简易版之最短距离 --- 水题

HDU 2083 简易版之最短距离

/* HDU 2083 简易版之最短距离 */
#include <cstdio>
#include <algorithm>
using namespace std;

const int maxn = 505;
int a[maxn];

int main()
{
#ifdef _LOCAL
    freopen("D:\input.txt", "r", stdin);
#endif

    int t;
    scanf("%d", &t);
    while (t--){
        int n;
        scanf("%d", &n);
        for (int i = 1; i <= n; ++i){
            scanf("%d", a + i);
        }
        sort(a + 1, a + n + 1); //处理6 4 2这种输入
        int ans = 10000 * 505; //定义最大值
        for (int i = 1; i <= n; ++i){
            //以i为起点
            int sum = 0;
            //加上到i之前的点的距离的和
            for (int j = 1; j < i; ++j){
                sum += (a[i] - a[j]);
            }//for(j)
            //加上到i之后的点的距离的和
            for (int j = i + 1; j <= n; ++j){
                sum += (a[j] - a[i]);
            }
            //若总和更小则更新总和
            if (sum < ans){
                ans = sum;
            }
        }//for(i)
        printf("%d
", ans);

    }//while(t)

    return 0;
}
View Code
原文地址:https://www.cnblogs.com/tommychok/p/5081372.html