HDU-4311 meeting point-1 Manhattan distance quick computing

Source: Internet
Author: User

This question has a certain skill, need to calculate the meaning of a point in the time complexity of nlog (N), N-1 points to the distance between the sum, here need to use such a technique, calculate the distance from X and Y separately. First, calculate the distance from the X axis, then sort the order first, and then sum the distance to the point P (P-1) * XP-sum (x1... xp-1) + sum (XP + 1... XN)-(N-P) * XP; similarly, the distance from the Y axis can be calculated, which is accumulated to a struct. So you can directly find the minimum value.

The Code is as follows:

#include <cstdlib>#include <cstring>#include <cstdio>#include <cmath>#include <algorithm>using namespace std;typedef long long int Int64;int N;struct Point{    Int64 x, y, sum;}e[100005];bool cmpx(Point a, Point b){    return a.x < b.x;}bool cmpy(Point a, Point b){    return a.y < b.y;    }int main(){    int T;    Int64 sum, Min;    scanf("%d", &T);    while (T--) {        sum = 0;        Min = 1LL << 62;        scanf("%d", &N);        for (int i = 1; i <= N; ++i) {            e[i].sum = 0;            scanf("%I64d %I64d", &e[i].x, &e[i].y);        }        sort(e+1, e+1+N, cmpx);        for (int i = 1; i <= N; ++i) {            e[i].sum += (i-1) * e[i].x - sum;            sum += e[i].x;        }        sum = 0;        for (int i = N; i >= 1; --i) {            e[i].sum += sum - (N-i) * e[i].x;            sum += e[i].x;        }        sum = 0;        sort(e+1, e+1+N, cmpy);        for (int i = 1; i <= N; ++i) {            e[i].sum += (i-1) * e[i].y -sum;            sum += e[i].y;        }        sum = 0;        for (int i = N; i >= 1; --i) {            e[i].sum += sum - (N-i) * e[i].y;            Min = min(Min, e[i].sum);            sum += e[i].y;        }        printf("%I64d\n", Min);    }    return 0;}

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.