这题的关键在于转化曼哈顿距离为契比雪夫距离
由一个加法变成一个取max
我们重新定义一个坐标为
(
x
,
y
)
(x,y)
(x,y)的点的坐标为
(
x
+
y
,
x
−
y
)
(x+y,x-y)
(x+y,x−y)
这样,两个点的距离就变成了
m
a
x
(
x
1
,
−
x
2
,
,
y
1
,
−
y
2
,
)
max(x_1^,-x_2^,,y_1^,-y_2^,)
max(x1,−x2,,y1,−y2,)
我们使用双指针维护,保证在当前区间内x的差值不超过要求
然后使用平衡树维护y坐标,把符合坐标的并查集到一起
这里比较难写,因为返回的不是权值是前驱后继的编号
笔者写的是treap,比较熟练
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<queue>
#define lch(x) tr[x].leftson
#define rch(x) tr[x].rightson
#define v(x) tr[x].val
#define c(x) tr[x].cir
#define p(x) tr[x].random
#define s(x) tr[x].size
#define id(x) tr[x].id
using namespace std;
const int maxn = 100007;
struct node{int random,val,leftson,rightson,cir,size,id;}tr[maxn];
struct no{int x,y;}cow[maxn];
int n,cc,root,cnt,f[maxn],f1,f2,q[maxn],used[maxn];
int Abs(int x){return x<0?-x:x;}
bool cmp1(no a,no b){return a.x<b.x;}
int find(int x){return f[x]==x?x:f[x]=find(f[x]);}
void pushup(int k){s(k)=s(lch(k))+s(rch(k));}
int New(int val,int pos){
cnt++;v(cnt)=val;id(cnt)=pos;
p(cnt)=rand();s(cnt)=1;return cnt;
}
void LR(int &k){
int y=rch(k);
rch(k)=lch(y);lch(y)=k;
s(y)=s(k);pushup(k);k=y;
}
void RR(int &k){
int y=lch(k);
lch(k)=rch(y);rch(y)=k;
s(y)=s(k);pushup(k);k=y;
}
void insert(int &k,int val,int pos){
if(!k){k=New(val,pos);return;}
s(k)++;
if(v(k)>=val){
insert(lch(k),val,pos);
if(p(lch(k))<p(k))RR(k);
}
else{
insert(rch(k),val,pos);
if(p(rch(k))<p(k))LR(k);
}
}
void del(int &k,int num,int pos)
{
if(!k)return;s(k)--;
if(v(k)==num&&id(k)==pos){
if(lch(k)*rch(k)==0){k=rch(k)+lch(k);return;}
else{
if(p(lch(k))<p(rch(k)))RR(k),del(k,num,pos);
else LR(k),del(k,num,pos);
}
}
else if(num<v(k))del(lch(k),num,pos);
else del(rch(k),num,pos);
}
void queryFront(int rt,int key){
if(!rt)return;
if(key>=v(rt)){
f1=rt;
queryFront(rch(rt),key);
}
else queryFront(lch(rt),key);
}
void queryLast(int rt,int key){
if(!rt)return;
if(key<v(rt)){
f2=rt;
queryLast(lch(rt),key);
}
else queryLast(rch(rt),key);
}
int main(){
scanf("%d%d",&n,&cc);
for(int i=1;i<=n;i++){
int x,y;
f[i]=i;scanf("%d%d",&x,&y);
cow[i].x=x+y,cow[i].y=x-y;
}
sort(cow+1,cow+1+n,cmp1);
int head=1,tail=0;
for(int i=1;i<=n;i++){
while(head<=tail&&cow[i].x-cow[q[head]].x>cc){
del(root,cow[q[head]].y,q[head]);
head++;
}
f1=f2=0;
queryFront(root,cow[i].y);
queryLast(root,cow[i].y);
if(f1!=0&&Abs(v(f1)-cow[i].y)<=cc){
if(find(i)!=find(id(f1))){
f[find(i)]=find(id(f1));
}
}
if(f2!=0&&Abs(v(f2)-cow[i].y)<=cc){
if(find(i)!=find(id(f2))){
f[find(i)]=find(id(f2));
}
}
insert(root,cow[i].y,i);
q[++tail]=i;
}
int ans=0,ans2=0;
for(int i=1;i<=n;i++){
if(used[find(i)]==0)ans++;
used[find(i)]++;
ans2=max(ans2,used[find(i)]);
}
cout<<ans<<" "<<ans2;
}