HDU-4311 Meeting point-1 曼哈顿距离快速计算

该题具有一定的技巧性,需要在Nlog(N)的时间复杂度下计算出任意一个点,N-1个点到其的距离综和,这里需要运用这样一个技巧,将x,y分开计算,首先计算x轴的距离,那么就先排一次序,然后有到P号点的距离和为 (P-1) * Xp - sum(X1...Xp-1) + sum(Xp+1...Xn) - (N-P) * xp; 同理可计算出y轴的距离,这两个距离是累加到一个结构体上的。所以最后直接找最小值即可。

代码如下:

#include 
#include 
#include 
#include 
#include 
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;
}

你可能感兴趣的:(HDU-4311 Meeting point-1 曼哈顿距离快速计算)