[Tjoi 2013]松鼠聚会

时间:2023-03-09 08:49:18
[Tjoi 2013]松鼠聚会

3170: [Tjoi 2013]松鼠聚会

Time Limit: 10 Sec  Memory Limit: 128 MB
Submit: 1318  Solved: 664
[Submit][Status][Discuss]

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

HINT

Source

  暴力算法O(n2),直接暴力枚举每一个点作为集合点,然后计算距离。

提供一种太暴力的做法  运用贪心策略

  我们发现应该尽量让松鼠少走路,那么集合点应该尽量靠近中间,计算时间复杂度发现差不多可以扫1000个点

那我们就可以避免扫10W而去扫(n/2-500,n/2+500),不断更新答案,理论上可以被卡掉。。但是貌似还没被卡过??

  然后说正解:

    题目要求的是Max(|x1-x2|,|y1-y2| );    求得是切比雪夫距离

  切比雪夫是啥??不喜欢他(她?)。。我们还是换成曼哈顿吧

  简单证明一下:

      对于曼哈顿距离,d=(|x1-x2|+|y1-y2|);

  我们把式子展开:

  d=Max(Max(x1-x2,x2-x1)+Max(y1-y2,y2-y1))

  d=Max(x1-x2+y1-y2,x1-x2+y2-y1,x2-x1+y1-y2,x2-x1+y2-y1)

  将同一个坐标合并起来:发现:

  d=Max( (x1+y1) - (x2+y2 ) , (x1-y1)-(x2-y2), -(x1-y1)+(x2-y2),-(x1+y1)+(x2+y2))

  d=Max( | (x1+y1) -(x2+y2) |,| (x1-y1)-(x2-y2) | )

所以x=x1+y1,y=x1-y1 就转化成了切比雪夫距离,换一下元

x=(x+y)/2,y=(x-y)/2就是把切比雪夫转化为曼哈顿

我们在排一下序,求个前缀和就完事了

    

 #include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
struct sta{
ll x,y;
}k[]; template <typename _t>
inline _t read(){
_t sum=,f=;char ch=getchar();
while(ch<''||ch>''){if(ch=='-')f=-;ch=getchar();}
while(ch>=''&&ch<=''){sum=sum*+ch-'',ch=getchar();}
return sum*f;
} int n;
int lx[],ly[];
ll sumx[],sumy[];
int main(){
n=read<int>();
for(int i=;i<=n;++i){
int x,y;
x=read<int>(),y=read<int>();
k[i].x=lx[i]=x+y,k[i].y=ly[i]=x-y;
}
sort(lx+,lx+n+);sort(ly+,ly+n+);
for(int i=;i<=n;++i)
sumx[i]=sumx[i-]+lx[i],
sumy[i]=sumy[i-]+ly[i];
ll ans=(ll)1e30;
for(int i=;i<=n;++i){
int pos=lower_bound(lx+,lx+n+,k[i].x)-lx;
ll sum=sumx[n]-sumx[pos]-k[i].x*(n-pos)+k[i].x*pos-sumx[pos];
pos=lower_bound(ly+,ly+n+,k[i].y)-ly;
sum+=sumy[n]-sumy[pos]-k[i].y*(n-pos)+k[i].y*pos-sumy[pos];
ans=min(ans,sum);
}
printf("%lld\n",ans>>);
return ;
}