关于理解扫描线的几个不错的博客:
https://www.luogu.com.cn/blog/paperghost/ls-xue-xi-bi-ji-note37-sao-miao-xian-line-sweep-algorithm
https://blog.csdn.net/sslz_fsy/article/details/82902644
板子:
#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<cstdio>
#include<algorithm>
#define debug(a) cout<<#a<<"="<<a<<endl;
using namespace std;
const int maxn=2e5+500;
typedef long long LL;
LL n,ans,cnt;
LL y[maxn];//用来离散化
struct smx
{
LL y1,y2,x,mark;//标记入边还是出边
bool operator < (const smx&a) const{
return x<a.x;
}
}line[maxn];
struct SegmentTree
{
LL l,r,tag,len;
}tree[maxn*8];
void build(LL p,LL l,LL r)
{
tree[p].l=l;tree[p].r=r;
if(l==r) return;
LL mid=(tree[p].l+tree[p].r)/2;
build(p*2,l,mid);
build(p*2+1,mid+1,r);
}
void spread(LL p)
{
if(tree[p].tag) tree[p].len=y[tree[p].r+1]-y[tree[p].l];
else tree[p].len=tree[p*2].len+tree[p*2+1].len;
}
void change(LL p,LL l,LL r,LL k)
{
if(l<=tree[p].l&&r>=tree[p].r)
{
tree[p].tag+=k;
spread(p);
return;
}
LL mid=(tree[p].l+tree[p].r)/2;
if(l<=mid) change(p*2,l,r,k);
if(r>mid) change(p*2+1,l,r,k);
spread(p);
}
int main(void)
{
cin.tie(0);std::ios::sync_with_stdio(false);
cin>>n;
for(LL i=1;i<=n;i++)
{
LL _x1,_x2,_y1,_y2;cin>>_x1>>_y1>>_x2>>_y2;
y[i*2-1]=_y1;y[i*2]=_y2;
line[i*2-1]=(smx){_y1,_y2,_x1,1};line[i*2]=(smx){_y1,_y2,_x2,-1};
}
n=n*2;
sort(y+1,y+1+n);//离散化
sort(line+1,line+1+n);//按照x坐标的大小排序
cnt=unique(y+1,y+n+1)-(&y[1])-1;//去重操作计算有多少个不同的y,也就是这个图象有几个y。因为区间[l,r]表示的是[l,r+1],所以区间[l,r-1]实际上是[l,r],所以总区间长度cnt要多减一个1
build(1,1,cnt);
for(LL i=1;i<n;i++)
{
LL y1=lower_bound(y+1,y+cnt+2,line[i].y1)-y;//当前这条线段的y1坐标的离散值 ,表示线段的y1是在线段树的第(离散值)个节点
LL y2=lower_bound(y+1,y+cnt+2,line[i].y2)-y-1;//当前这条线段的y2坐标的离散值,表示线段的y2是在线段树的第(离散值)个节点,同时为了实际上是求[l,r],所以我们要求的是[l,r-1],所以这里要减1
change(1,y1,y2,line[i].mark);
ans+=tree[1].len*(line[i+1].x-line[i].x);
}
cout<<ans<<endl;
return 0;
}