51nod1108(距离之和最小V2)

题目链接:https://www.51nod.com/onlineJudge/submitDetail.html#!judgeId=306798

题目说的是“求一个点使它到这N个点的曼哈顿距离之和最小”,并不是说“在这些点里找出一个点”,所以,把三个坐标分别排序,分别取中间的那一个坐标即可。

#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;

const int maxn = 10000 + 10;

int x[maxn];
int y[maxn];
int z[maxn];
int n;

int main()
{
    scanf("%d", &n);
    for (int i=0; i<n; i++) scanf("%d%d%d", &x[i], &y[i], &z[i]);

    sort(x, x+n);
    sort(y, y+n);
    sort(z, z+n);

    long long ans = 0;
    int m = n >> 1;
    for (int i=0; i<n; i++){
        ans += (long long)(abs(x[i]-x[m]) + abs(y[i]-y[m]) + abs(z[i]-z[m]));
    }
    cout << ans << endl;
    return 0;
}


猜你喜欢

转载自blog.csdn.net/qust1508060414/article/details/76706369