题意
给定N个点的x、y坐标,一个可平移的W*H的矩阵,问最多能用这个矩阵框住多少个点。 (1<=N<=10000, 1<=W,H<=40000, -20000<=x,y<=20000, )
每个点扩展一个W*H的矩阵,点处在左下角,用线段树扫描线来做。
每个矩阵左边为进边,权值为1,右边为负边,权值为-1;线段树维护进、出边的两端点的区间最大值,表示更新此边后最多重叠矩形个数。
代码
#include<cmath>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<set>
#include<map>
#include<list>
#include<stack>
#include<queue>
#include<vector>
#define cl (k<<1)
#define cr (k<<1|1)
#define Mid ((a[k].l+a[k].r)>>1)
#define mem(a,x) memset(a,x,sizeof(a))
using namespace std;
#define bug printf("???\n")
typedef long long LL;
const int Inf=0x3f3f3f3f;
const double eps=1e-7;
const int maxn=1e4+50;
int x[maxn],y[maxn];
struct Line{ //要扫描的边,进边&出边组成一个矩形
int x, y1, y2, tp;
friend bool operator<(const Line&a,const Line&b){
if(a.x!=b.x) //x坐标小的在前,进边在前
return a.x < b.x;
else
return a.tp > b.tp;
}
Line(){}
Line(int a,int b,int c,int d):x(a),y1(b),y2(c),tp(d){}
}line[maxn*2];
struct N{ //维护区间最大值
int l,r,ma,lz;
}a[maxn*2*4];
int ls[maxn*2], cur;
int gs(int x){return lower_bound(ls+1, ls+1+cur, x)-ls;}
void build(int k,int l,int r){
a[k].l = l, a[k].r = r;
a[k].ma = a[k].lz = 0;
if(l==r) return;
build(cl, l, Mid);
build(cr, Mid+1, r);
}
void down(int k){
a[cl].ma += a[k].lz;
a[cr].ma += a[k].lz;
a[cl].lz += a[k].lz;
a[cr].lz += a[k].lz;
a[k].lz = 0;
}
void update(int k,int l,int r,int x){
if(l<=a[k].l&&a[k].r<=r){
a[k].lz += x;
a[k].ma += x;
return;
}
if(a[k].lz) down(k);
if(l<=Mid) update(cl, l, r, x);
if(r> Mid) update(cr, l, r, x);
a[k].ma = max(a[cl].ma, a[cr].ma);
}
int main()
{
int N,W,H;
while(cin>>N, N>=0){
cur = 0;
cin>>W>>H;
for(int i=1; i<=N; i++){
scanf("%d%d",&x[i],&y[i]);
line[i*2-1] = Line(x[i], y[i], y[i]+H, 1); //进边
line[i*2] = Line(x[i]+W, y[i], y[i]+H, -1); //出边
ls[++cur] = y[i]; //离散化边的两端
ls[++cur] = y[i]+H; //
}
sort(line+1, line+1+N*2);
sort(ls+1, ls+1+cur);
cur = unique(ls+1, ls+1+cur) - (ls+1);
build(1, 1, cur);
int ans=0;
for(int i=1; i<=N*2; i++){
update(1, gs(line[i].y1), gs(line[i].y2), line[i].tp);
ans = max(ans, a[1].ma);
}
cout<<ans<<endl;
}
}