题解:切比雪夫距离转化为曼哈顿距离
枚举源点,横纵坐标互不影响,分开考虑,前缀和优化
横纵分开考虑是一种解题思路
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; typedef long long Lint; const int maxn=100009; Lint ans=1000000000000000000LL; int n; int px[maxn],py[maxn]; int a[maxn]; Lint sa[maxn][2]; int b[maxn]; Lint sb[maxn][2]; int main(){ scanf("%d",&n); for(int i=1;i<=n;++i){ int x,y; scanf("%d%d",&x,&y); px[i]=x+y; py[i]=x-y; a[i]=x+y; b[i]=x-y; } sort(a+1,a+1+n); sort(b+1,b+1+n); for(int i=1;i<=n;++i){ sa[i][0]=sa[i-1][0]+a[i]-a[1]; sb[i][0]=sb[i-1][0]+b[i]-b[1]; } for(int i=n;i>=1;--i){ sa[i][1]=sa[i+1][1]+a[n]-a[i]; sb[i][1]=sb[i+1][1]+b[n]-b[i]; } for(int i=1;i<=n;++i){ int pa=lower_bound(a+1,a+1+n,px[i])-a; int pb=lower_bound(b+1,b+1+n,py[i])-b; Lint tm=0; tm+=(sa[1][1]-sa[pa][1])-1LL*(a[n]-a[pa])*(pa-1); tm+=(sa[n][0]-sa[pa][0])-1LL*(a[pa]-a[1])*(n-pa); tm+=(sb[1][1]-sb[pb][1])-1LL*(b[n]-b[pb])*(pb-1); tm+=(sb[n][0]-sb[pb][0])-1LL*(b[pb]-b[1])*(n-pb); ans=min(ans,tm); } printf("%lld ",ans/2); return 0; }