[TJOI2013]松鼠聚会

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

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

Output
表示为了聚会走的路程和最小为多少。

Sample Input
6
-4 -1
-1 -2
2 -4
0 2
0 3
5 -2

Sample Output
20


如果是曼哈顿距离十分好求,我们可以分开考虑

将x排序,利用前缀后缀和,算出每个点在x轴方向到其他点的距离,将答案记录下来,再按y排序,即可统计答案

但是这题并不是曼哈顿距离,而是切比雪夫距离,怎么办?

其实有个结论,将每个点的坐标改为((frac{x+y}{2},frac{x-y}{2}))后,两点之间的曼哈顿距离等于切比雪夫距离

证明的话可以自己手推,记得考虑大小关系(其实是我懒了)

这种结论题。。。不知道结论根本不会写吧。。。至少我是没有当场推结论的水平。。。

/*program from Wolfycz*/
#include<cmath>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define inf 0x7f7f7f7f
using namespace std;
typedef long long ll;
typedef unsigned int ui;
typedef unsigned long long ull;
inline char gc(){
	static char buf[1000000],*p1=buf,*p2=buf;
	return p1==p2&&(p2=(p1=buf)+fread(buf,1,1000000,stdin),p1==p2)?EOF:*p1++;
}
inline int frd(){
	int x=0,f=1; char ch=gc();
	for (;ch<'0'||ch>'9';ch=gc())	if (ch=='-')	f=-1;
	for (;ch>='0'&&ch<='9';ch=gc())	x=(x<<3)+(x<<1)+ch-'0';
	return x*f;
}
inline int read(){
	int x=0,f=1; char ch=getchar();
	for (;ch<'0'||ch>'9';ch=getchar())	if (ch=='-')	f=-1;
	for (;ch>='0'&&ch<='9';ch=getchar())	x=(x<<3)+(x<<1)+ch-'0';
	return x*f;
}
inline void print(int x){
	if (x<0)	putchar('-'),x=-x;
	if (x>9)	print(x/10);
	putchar(x%10+'0');
}
const int N=1e5;
struct S1{
	int x,y,ID;
	void insert(int _x,int _y,int _ID){x=_x,y=_y,ID=_ID;}
}A[N+10];
bool cmpx(const S1 &x,const S1 &y){return x.x<y.x;}
bool cmpy(const S1 &x,const S1 &y){return x.y<y.y;}
ll pre[N+10],suf[N+10],v[N+10];
int main(){
	int n=read(); ll Ans=1e18;
	for (int i=1;i<=n;i++){
		int x=read(),y=read();
		A[i].insert(x+y,x-y,i);
	}
	sort(A+1,A+1+n,cmpx);
	for (int i=1;i<=n;i++)	pre[i]=pre[i-1]+A[i].x;
	for (int i=n;i>=1;i--)	suf[i]=suf[i+1]+A[i].x;
	for (int i=1;i<=n;i++)	v[A[i].ID]=(1ll*i*A[i].x-pre[i])+(suf[i]-1ll*(n-i+1)*A[i].x);
	sort(A+1,A+1+n,cmpy);
	for (int i=1;i<=n;i++)	pre[i]=pre[i-1]+A[i].y;
	for (int i=n;i>=1;i--)	suf[i]=suf[i+1]+A[i].y;
	for (int i=1;i<=n;i++)	Ans=min(Ans,(1ll*i*A[i].y-pre[i])+(suf[i]-1ll*(n-i+1)*A[i].y)+v[A[i].ID]);
	printf("%lld
",Ans>>1);
	return 0;
}
原文地址:https://www.cnblogs.com/Wolfycz/p/10000289.html