点头 距离之和最小 V2

题目链接:http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1108

题目描述:

1108 . 距离之和最小 V2
基准时间限制:1 秒 空间限制:65536 KB 分值: 40
三维空间上有N个点, 求一个点使它到这N个点的曼哈顿距离之和最小,输出这个最小的距离之和。
点(x1,y1,z1)到(x2,y2,z2)的曼哈顿距离就是|x1-x2| + |y1-y2| + |z1-z2|。即3维坐标差的绝对值之和。
Input
第1行:点的数量N。(2 <= N <= 10000)
第2 - N + 1行:每行3个整数,中间用空格分隔,表示点的位置。(-10^9 <= X[i], Y[i], Z[i] <= 10^9)
Output
输出最小曼哈顿距离之和。
Input 示例
4
1 1 1
-1 -1 -1
2 2 2
-2 -2 -2
Output 示例
18
解题思路:三维的距离可以拆分成一维的距离来做,因为马哈顿距离x、y、z相互是没有影响的!!!

//#pragma comment(linker,"/STACK:102400000,102400000")
#include<stdio.h>
#include<iostream>
#include<string.h>
#include<math.h>
#include<algorithm>
#include<vector>
#include<map>
#include<set>
#include<queue>
#include<string>
#define ll long long
#define db double
#define PB push_back
#define lson k<<1
#define rson k<<1|1
using namespace std;

const int N = 10005;
ll x[N],y[N],z[N];

int main()
{
#ifdef PKWV
    freopen("in.in","r",stdin);
#endif // PKWV
    int n;
    while(scanf("%d",&n)+1)
    {
        for(int i=0;i<n;i++) scanf("%I64d%I64d%I64d",&x[i],&y[i],&z[i]);
        sort(x,x+n),sort(y,y+n),sort(z,z+n);
        int k=n/2;
        ll res=0;
        for(int i=0;i<n;i++) res+=abs(x[i]-x[k])+abs(y[i]-y[k])+abs(z[i]-z[k]);
        printf("%I64d\n",res);
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值