P5490 【模板】扫描线

关于理解扫描线的几个不错的博客:

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;
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值