扫描线 (线段树)

【模板】扫描线 - 洛谷

昨天脑子不好使,拖了一天才搞懂啊。

其实就是按高度排序后维护行的宽度吧。

那么只有两种情况:当前节点的cnt>0和==0的情况。

前一种对应整段都覆盖,因为我们只对全覆盖的线段++cnt;所以都加上。

后一种对应其他情况,统计子节点即可。因为我们最多更改到当前节点,所以子节点的信息是正确的。

/*keep on going and never give up*/
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define db(x) cerr<<(#x)<<" "<<(x)<<" "<<endl;
#define endl "\n"
#define fast std::ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
const int maxn = 1e6+10;
int n,cnt=0;
int X[maxn<<1];
struct scanline{
	int l,r,h;
	int mark;
	bool operator<(const scanline &t)const{
		return h<t.h;
	} 
}line[maxn<<1];
struct sgtree{
	int l,r,cnt;
	int len;	
}t[maxn<<2];
void build(int p,int l,int r){
	t[p].l=l,t[p].r=r;
	t[p].len=0;t[p].cnt=0;
	if(l==r)return;
	int mid=(l+r)>>1;
	build(p<<1,l,mid);
	build(p<<1|1,mid+1,r);
}
void pushup(int p){
	int l=t[p].l,r=t[p].r;
	if(t[p].cnt)t[p].len=X[r+1]-X[l];
	else t[p].len=t[p<<1].len+t[p<<1|1].len;
}
void change(int p,int l,int r,int op){
	int nl=t[p].l,nr=t[p].r;
	if( X[nr+1]<=l||r<=X[nl])return; 
	if(l<=X[nl]&&X[nr+1]<=r){
		t[p].cnt+=op;
		pushup(p);
		return;
	}
	change(p<<1,l,r,op);
	change(p<<1|1,l,r,op);
	pushup(p);
}
signed main(){
	fast
	cin>>n;
	for(int i=1;i<=n;i++){
		int x1,x2,y1,y2;
		cin>>x1>>y1>>x2>>y2;
		X[2*i-1]=x1,X[2*i]=x2;
		line[2*i-1]=(scanline){x1,x2,y1,1};
		line[2*i]=(scanline){x1,x2,y2,-1};
	}
	n<<=1;
	sort(line+1,line+n+1);
	sort(X+1,X+n+1);
	int tot=unique(X+1,X+n+1)-(X+1);
	build(1,1,tot-1);
	int ans=0;
	for(int i=1;i<n;i++){
		change(1,line[i].l,line[i].r,line[i].mark);
		ans+=t[1].len*(line[i+1].h-line[i].h);
	}
	cout<<ans;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值