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