Portal
There are n points in the three-dimensional space, and the sum of the smallest distances is obtained by a point that makes it to the minimum of the Manhattan distance of the N-point.
Point (X1,Y1,Z1) to (X2,Y2,Z2) The Manhattan distance is |x1-x2| + |y1-y2| + |z1-z2|. That is, the sum of the absolute values of the 3-dimensional coordinate difference.
Input
Line 1th: number of points N. (2 <= N <= 10000)
2-n + 1 lines: 3 integers per line, separated by a space, to indicate the position of the point. ( -10^9 <= x[i], y[i], Z[i] <= 10^9)
Output
Outputs the sum of the smallest Manhattan distances.
Input example
4
1 1 1
-1-1-1
2 2 2
-2-2-2
Output example
18
Problem Solving Ideas:
This topic we can think of, because this is a three-dimensional coordinates, so we think the whole thing is not very good to think, then we will divide the problem, because the Manhattan distance is |x1-x2| + |y1-y2| + |z1-z2|, so we can find the minimum value of x-coordinate, the minimum value of the y-coordinate, the minimum value of the z-coordinate, then the final result is definitely the sum of the three minimum values, in fact, this is also reflected the idea of rounding, if it is a single axis, the problem is simple, is to find a median , sort out the intermediary ah that's OK.
My Code:
#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>#include <cstdlib>#include <cmath>using namespace STD;Const intMAXN =1e4+5;typedef Long LongLL;DoubleX[MAXN],Y[MAXN],Z[MAXN];intMain () {intN while(~scanf("%d", &n)) { for(intI=0; i<n; i++)scanf("%LF%LF%LF", &x[i],&y[i],&z[i]);DoubleSUM1 =0, sum2 =0, sum3 =0; Sort (x, x+n);Doublexx = x[n/2]; Sort (y, y+n);Doubleyy = y[n/2]; Sort (z, z+n);DoubleZZ = z[n/2]; for(intI=0; i<n; i++) Sum1 + =fabs(X[I]-XX); for(intI=0; i<n; i++) sum2 + =fabs(Y[I]-YY); for(intI=0; i<n; i++) Sum3 + =fabs(Z[I]-ZZ);printf("%.0lf\n", sum1 + sum2 + sum3); }return 0;}
51NOD 1108 Distance and minimum V2 (median + rounding)