cdq分治学习笔记
属于离线分治算法的一种,一般用于偏序类问题维护时降维处理。
#include <bits/stdc++.h>
using namespace std;
inline int read()
{
int x=0;int f=1;char ch=getchar();
while(!isdigit(ch)){if(ch=='-')f=-1;ch=getchar();}
while(isdigit(ch)){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
const int MAXN = 1000005;
struct Node {int x,y,z;};
Node a[MAXN],b[MAXN];
int c[MAXN],ans[MAXN];
int n,m,t,tot;
bool operator < (const Node &a,const Node &b)
{return a.x<b.x || a.x==b.x && a.y<b.y;}
inline int ask(int x)
{
int y=-(1<<30);
for (; x; x-=x&-x) y=max(y,c[x]);
return y;
}
inline void insert(int x,int y)
{
for (; x<tot; x+=x&-x)
c[x]=max(c[x],y);
}
inline void calc(int st,int ed,int de,int dx,int dy)
{
for (int i=st; i != ed; i+=de)
{
int y=dy==1 ? b[i].y : tot - b[i].y;
int temp=dx*b[i].x+dy*b[i].y;
if (a[b[i].z].z==1) insert(y,temp);
else ans[b[i].z]=min(ans[b[i].z],abs(temp - ask(y)));
}
for (int i=st; i != ed; i+=de)
{
int y=dy==1 ? b[i].y : tot - b[i].y;
if (a[b[i].z].z==1)
for (int j=y; j<tot; j+=j&-j) c[j]=-(1<<30);
}
}
void cdqdiv(int l,int r)
{
int mid=(l+r)>>1;
if (l<mid) cdqdiv(l,mid);
if (mid+1<r) cdqdiv(mid+1,r);
t=0;
for (int i=l; i<=r; i++)
if (i<=mid && a[i].z==1 || i > mid && a[i].z==2)
b[++t]=a[i],b[t].z=i;
sort(b+1,b+t+1);
calc(1,t+1,1,1,1),calc(t,0,-1,-1,-1);
calc(1,t+1,1,1,-1),calc(t,0,-1,-1,1);
}
int main()
{
n=read(); m=read()+n;
for (int i=1; i<=n; i++)
a[i].x=read(),a[i].y=read()+1,a[i].z=1;
for (int i=n+1; i<=m; i++)
a[i].z=read(),a[i].x=read(),a[i].y=read()+1;
for (int i=1; i<=m; i++)
tot=max(tot,a[i].y);
tot++;
memset(c,0xcf,sizeof(c));
memset(ans,0x3f,sizeof(ans));
cdqdiv(1,m);
for (int i=1; i<=m; i++)
if (a[i].z==2) printf("%d\n",ans[i]);
return 0;
}