CodeForces 610 D.Vika and Segments(线段树+扫描线)

来源:互联网 发布:淘宝日系原单店铺推荐 编辑:程序博客网 时间:2024/05/22 11:42

Description
求矩形面积并
Input
第一行一整数n表示矩形个数,之后n行每行四个整数x1,y1,x2,y2表示矩形的一对顶点(1<=n<=1e5,-1e9<=x1,y1,x2,y2<=1e9)
Output
输出矩形面积并
Sample Input
3
0 1 2 1
1 4 1 2
0 3 2 3
Sample Output
8
Solution
用上下两条线段表示一个矩形,下边权值为1,上边权值为-1,对横坐标离散化后建线段树,维护该区间被覆盖的线段长度,对纵坐标排序一条条扫线段,两个不同纵坐标的线段之间的面积就是横坐标被覆盖的线段长度乘上纵坐标的差值
Code

#include<cstdio>#include<iostream>#include<cstring>#include<algorithm>#include<cmath>#include<vector>#include<queue>#include<map>#include<set>#include<ctime>using namespace std;typedef long long ll;#define INF 0x3f3f3f3f#define maxn 222222int n;struct node{    int x1,x2,y,type;    node(){};    node(int _x1,int _x2,int _y,int _type)    {        x1=_x1,x2=_x2,y=_y,type=_type;    }    bool operator <(const node&b)const    {        return y<b.y;    }}e[maxn];int h[maxn];//离散化横坐标ll len[maxn<<3],cover[maxn<<3];#define ls (t<<1)#define rs ((t<<1)|1)void push_up(int l,int r,int t){    if(cover[t]>0)len[t]=h[r]-h[l];    else     {        if(l==r)len[t]=0;        else len[t]=len[ls]+len[rs];    }}void update(int L,int R,int l,int r,int t,int v){    if(l==r)return ;    if(L<=l&&R>=r)cover[t]+=v;    else    {        int mid=(l+r)>>1;        if(mid>L)update(L,R,l,mid,ls,v);        if(mid<R)update(L,R,mid,r,rs,v);    }    push_up(l,r,t);}int main(){    while(~scanf("%d",&n))    {        int res=0;        for(int i=1;i<=n;i++)        {            int x1,y1,x2,y2;            scanf("%d%d%d%d",&x1,&y1,&x2,&y2);            if(x1>x2||y1>y2)swap(x1,x2),swap(y1,y2);            x1--,y1--;            e[res]=node(x1,x2,y1,1),h[res++]=x1;            e[res]=node(x1,x2,y2,-1),h[res++]=x2;        }        sort(h,h+res);        res=unique(h,h+res)-h;        memset(len,0,sizeof(len));        memset(cover,0,sizeof(cover));        sort(e,e+2*n);        ll ans=0;        for(int i=0;i<2*n-1;i++)        {            int L=lower_bound(h,h+res,e[i].x1)-h;            int R=lower_bound(h,h+res,e[i].x2)-h;            update(L,R,0,res-1,1,e[i].type);            ans+=1ll*len[1]*(e[i+1].y-e[i].y);        }        printf("%I64d\n",ans);    }    return 0;}
0 0
原创粉丝点击