扫描线学习笔记

· · 个人记录

#include <bits/stdc++.h>
using namespace std;

inline long long read()
{
    long long x=0;long long 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;
}

struct Node
{
    long long l,r,h,d;
    bool operator < (const Node &p) const
        { return h<p.h; }
};

const int MAXN = 500005;
typedef long long ll;
ll x[MAXN],cnt[MAXN<<2],sum[MAXN<<2];
Node line[MAXN];
ll n,m;

inline void pushup(ll p,ll l,ll r)
{
    if(cnt[p]) sum[p]=x[r+1]-x[l];
    else sum[p]=sum[p<<1]+sum[p<<1|1];
}

void update(ll p,ll l,ll r,ll ql,ll qr,ll v)
{
    if(ql<=l && qr>=r)
    {
       cnt[p]+=v; pushup(p,l,r);
       return;
    }
    ll mid=l+r>>1;
    if(ql<=mid) update(p<<1,l,mid,ql,qr,v);
    if(qr>mid)  update(p<<1|1,mid+1,r,ql,qr,v);
    pushup(p,l,r);
}

int main(int argc, char const *argv[])
{
    ll xl,yl,xr,yr,q=read();
    for(int i = 1; i <= q; ++i)
    {
        xl=read(),yl=read(),xr=read(),yr=read();
        x[++n]=xl; x[++n]=xr;
        line[++m]=(Node){xl,xr,yl,1};
        line[++m]=(Node){xl,xr,yr,-1};
    }
    sort(x+1,x+1+n);
    sort(line+1,line+1+m);
    ll ans=0,k=unique(x+1,x+n+1)-x-1;
    for(int i = 1; i < m; ++i)
    {
        ll l=lower_bound(x+1,x+k+1,line[i].l)-x;
        ll r=lower_bound(x+1,x+k+1,line[i].r)-x-1;
        if(l<=r) update(1,1,k-1,l,r,line[i].d);
        update(1,1,k-1,l,r,line[i].d);
        ans+=sum[1]*(line[i+1].h-line[i].h);
    }
    printf("%lld\n",ans);
    return 0;
}