51NOD 1108 Distance and minimum V2 (median + rounding)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.