跳到正文

个人记录

扫描线

ZsH68122zSh约 2 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年3月2日
篇幅
约 2 分钟

版本

  1. v2当前
  2. v1

矩形面积并

C++
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=1e5+10;
int n;
ll sum[N<<3],len[N<<3],a[N<<2];
ll ans;
struct scli{
	ll y1,y2,x,c;
};
vector<scli> sl;
bool cmp(const scli& i,const scli& j){
	return i.x<j.x;
}
void update(int x,int l,int r,int L,int R,ll k){
	if(r<L||l>R) return;
	if(L<=l&&r<=R) sum[x]+=k;
	else{
		int mid=l+((r-l)>>1);
		update(x<<1,l,mid,L,R,k);
		update(x<<1|1,mid+1,r,L,R,k);
	}
	if(sum[x]) len[x]=a[r+1]-a[l];
	else len[x]= (l==r) ? 0 : len[x<<1]+len[x<<1|1];
}
int main()
{
	scanf("%d",&n);
	for(int i=1;i<=n;i++){
		ll x1,y1,x2,y2;
		scanf("%lld %lld %lld %lld",&x1,&y1,&x2,&y2);
		a[(i<<1)-1]=y1,a[i<<1]=y2;
		sl.push_back((scli){y1,y2,x1,1}),sl.push_back((scli){y1,y2,x2,-1});
	}
	sort(a+1,a+(n<<1)+1);
	int m=unique(a+1,a+(n<<1)+1)-a-1;
	sort(sl.begin(),sl.end(),cmp);
	for(int i=0;i<sl.size();i++){
		int y1=lower_bound(a+1,a+m+1,sl[i].y1)-a,y2=lower_bound(a+1,a+m+1,sl[i].y2)-a;
		update(1,1,m-1,y1,y2-1,sl[i].c);
		if(i<sl.size()-1) ans+=len[1]*(sl[i+1].x-sl[i].x);
	}
	printf("%lld",ans);
	return 0;
}
原文