有无好心老哥帮调一下,wa了8个,赛事调了1h没调出来。
#include <unordered_map>
#include <algorithm>
#include <iostream>
#include <cstdio>
#include <cmath>
#define N 200005
#define LL long long
using namespace std;
int n,d,x[N],y[N];
unordered_map<int,int> mpx,mpy;
unordered_map<int,LL> sum,Numl;
LL calcy(int x) {
LL res=0;
for (int i=1;i<=n;i++) res+=abs(y[i]-x);
return res;
}
LL calcx(int y) {
LL res=0;
for (int i=1;i<=n;i++) res+=abs(x[i]-y);
return res;
}
int main() {
scanf("%d%d",&n,&d);
for (int i=1;i<=n;i++) scanf("%d%d",x+i,y+i),mpx[x[i]]++,mpy[y[i]]++;
sort(y+1,y+n+1);
sum[y[1]-d-1]=calcy(y[1]-d-1); int mn=y[1]-d-1;
for (int i=y[1]-d,numl=0,numr=n;i<=y[n]+d+1;i++) {
int res=sum[i-1];
res+=numl-numr;
if (mpy.count(i)) numr-=mpy[i],numl+=mpy[i];
sum[i]=res;
if (sum[i]<sum[mn]) mn=i;
}
int l=mn+1,r=mn-1;
sort(x+1,x+n+1);
LL dx=calcx(x[1]-d-1);
while (l>y[1]-d-1 and sum[l-1]<=d-dx) --l;
while (r<y[n]+d+1 and sum[r+1]<=d-dx) ++r;
int ans=max(0,(r-l+1));
for (int i=x[1]-d,numl=0,numr=n;i<=x[n]+d+1;i++) {
dx+=numl-numr;
if (mpx.count(i)) numr-=mpx[i],numl+=mpx[i];
while (l<=mn and sum[l]>d-dx) ++l;
while (l>y[1]-d-1 and sum[l-1]<=d-dx) --l;
while (r>=mn and sum[r]>d-dx) --r;
while (r<y[n]+d+1 and sum[r+1]<=d-dx) ++r;
ans+=max(0,(r-l+1));
}
printf("%d\n",ans);
return 0;
}