51nod1108(距离之和最小V2)

来源:互联网 发布:博客关注平台源码 编辑:程序博客网 时间:2024/06/01 19:14

题目链接: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;}


原创粉丝点击