bzoj3170 [Tjoi2013]松鼠聚会 切比雪夫距离转曼哈顿距离

Description


有N个小松鼠,它们的家用一个点x,y表示,两个点的距离定义为:点(x,y)和它周围的8个点即上下左右四个点和对角的四个点,距离为1。现在N个松鼠要走到一个松鼠家去,求走过的最短距离。

第一行给出数字N,表示有多少只小松鼠。0<=N<=10^5
下面N行,每行给出x,y表示其家的坐标。
-10^9<=x,y<=10^9

Solution


切比雪夫距离转曼哈顿距离,这是一道水题
原点坐标(x,y)变为(x+y,x-y),且原图两点切比雪夫距离变为新图曼哈顿距离的一半
反过来也成立
然后统计每个点到其它点的距离即可

Code


#include <stdio.h>
#include <string.h>
#include <algorithm>
#define rep(i,st,ed) for (int i=st;i<=ed;++i)

typedef long long LL;
const LL INF=1e15;
const int N=200005;

struct pos {
    LL x,y,ans;
} p[N];

int read() {
    int x=0,v=1; char ch=getchar();
    for (;ch<'0'||ch>'9';v=(ch=='-')?(-1):(v),ch=getchar());
    for (;ch<='9'&&ch>='0';x=x*10+ch-'0',ch=getchar());
    return x*v;
}

bool cmp(pos a,pos b) {
    return a.x<b.x;
}

void solve(int n) {
    std:: sort(p+1,p+n+1,cmp);
    LL tot=0;
    rep(i,2,n) {
        if (p[i].x!=p[i-1].x) tot+=(i-1)*1LL*(p[i].x-p[i-1].x);
        p[i].ans+=tot;
    }
}

int main(void) {
    int n=read();
    rep(i,1,n) p[i]=(pos) {read(),read()};
    rep(i,1,n) p[i]=(pos) {p[i].x+p[i].y,p[i].x-p[i].y};
    solve(n);
    rep(i,1,n) p[i].x=-p[i].x;
    solve(n);
    rep(i,1,n) std:: swap(p[i].x,p[i].y);
    solve(n);
    rep(i,1,n) p[i].x=-p[i].x;
    solve(n); LL prt=INF;
    rep(i,1,n) prt=std:: min(prt,p[i].ans);
    printf("%lld\n", prt/2);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值