HDU 4312 Meeting point-2(切比雪夫距离转换为曼哈顿距离优化枚举)

HDU 4312

题意

给你n个点求其中一个点到其他点 m a x ( ∣ x − x i ∣ , ∣ y − y i ) max(|x−x_{i}|,|y−y_{i}) max(xxi,yyi)之和的最小值

思路

m a x ( ∣ x − x i ∣ , ∣ y − y i ) max(|x−x_{i}|,|y−y_{i}) max(xxi,yyi)叫做切比雪夫距离直接求解的复杂度还是 O ( n 2 ) O(n^2) O(n2)的,但是可以利用一些方式来优化即,把切比雪夫距离转换成曼哈顿距离,再用求解曼哈顿距离的方式来求解,那么两者之间然后转换呢
首先我们可以在坐标系中画出两者到原点距离为1的点系,即有如下两个矩形
这里写图片描述
外面大矩形是切比雪夫距离为1的点系构成的矩形
内部是曼哈顿距离为1的矩形
所以如果我们要求解切比雪夫距离,我们可以把所有坐标进行旋转和缩放转换为求解曼哈顿距离
我们知道对于点 ( x , y ) (x,y) (x,y)绕原点逆旋转的的公式是
( x c o s θ + y s i n θ , y c o s θ − x s i n θ ) (xcos\theta+ysin\theta,ycos\theta-xsin\theta) (xcosθ+ysinθ,ycosθxsinθ)
所以我们将切比雪夫距离的矩形逆时针旋转 4 5 ∘ 45^{\circ} 45然后再缩小 2 \sqrt{2} 2 倍就得到了曼哈顿距离的矩形
所以两者的坐标转换为
( x + y 2 , x − y 2 ) (\frac{x+y}{2},\frac{x-y}{2}) (2x+y,2xy)
然后再用曼哈顿距离求法求解即可,因为可能存在浮点数精度的问题,所以我们在坐标的时候不除二,最后的答案除二即可

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <algorithm>
#include <math.h>
using namespace std;
const int maxn=100005;
struct Point
{
    long long x,y,id;
}a[maxn];
long long sumx[maxn],sumy[maxn];
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;
    scanf("%d",&t);
    while(t--)
    {
        memset(sumx,0,sizeof(sumx));
        memset(sumy,0,sizeof(sumy));
        int n;
        scanf("%d",&n);
        for(int i=1;i<=n;i++)
        {
            long long x,y;
            scanf("%lld%lld",&x,&y);
            a[i].x=x+y;
            a[i].y=y-x;
        }
        sort(a+1,a+n+1,cmpx);
        sumx[1]=a[1].x;
        a[1].id=1;
        for(int i=2;i<=n;i++)
        {
            sumx[i]=sumx[i-1]+a[i].x;
            a[i].id=i;
        }
        sort(a+1,a+n+1,cmpy);
        sumy[1]=a[1].y;
        for(int i=2;i<=n;i++)
            sumy[i]=sumy[i-1]+a[i].y;
        long long ans=1LL<<62;
        for(int i=1;i<=n;i++)
            ans=min(ans,sumy[n]-sumy[i]-(n-i)*a[i].y+i*a[i].y-sumy[i]+a[i].id*a[i].x-sumx[a[i].id]+sumx[n]-sumx[a[i].id]-(n-a[i].id)*a[i].x);
        printf("%lld\n",ans/2);
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值