点头 距离之和最小 V2

来源:互联网 发布:stata面板数据平衡命令 编辑:程序博客网 时间:2024/06/10 21:57

题目链接: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 示例
41 1 1-1 -1 -12 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|1using 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
原创粉丝点击