HDU 1542 Atlantis 线段树+扫描线

来源:互联网 发布:sql建一个销售表 编辑:程序博客网 时间:2024/05/17 07:44

题意:

求二维坐标下n个矩阵的面积并

分析:

如何求矩阵并的面积呢?如下图


我们可以利用扫描线来做,什么是扫描线?

你可以把这些矩阵合并后看做一个容器

现在你要把这些容器注满水

很明显:水先充满的地方为:


更据这样的思想就可以把原图分为下面几个部分惹:


那么如何用代码实现呢?

我们需要一个Seg结构体储存x方向线段 其中有4个参数 h--->线段高度 l--->左起位置  r---->右边结束   s---->是矩阵的上边or下边

///本题还需要对x坐标进行离散化

对所有线段排序后

这样,我们用扫描线去扫描每一条边的时候,都需要更新线段树的有效长度

是如何更新的呢?

如果扫到的这条边是某矩形的下边,则往区间插入这条线段

如果扫到的这条边是某矩形的上边,则往区间删除这条线段

每扫一个边就算一下当前的矩阵的面积 ans+=sum[1]*(ss[i+1].h-ss[i].h);

ACcode:

#include <bits/stdc++.h>#define maxn 222#define tmp (st<<1)#define mid ((l+r)>>1)#define lson l,mid,tmp#define rson mid+1,r,tmp|1using namespace std;int cnt[maxn<<2];double sum[maxn<<2];double x[maxn];struct Seg{    double h,l,r;    int s;    Seg(){}    Seg(double a,double b,double c,int d):l(a),r(b),h(c),s(d){}    bool operator<(const Seg &cmp)const{        return h<cmp.h;    }}ss[maxn];void push_up(int st,int l,int r){    if(cnt[st])sum[st]=x[r+1]-x[l];    else if(l==r)sum[st]=0;    else sum[st]=sum[tmp]+sum[tmp|1];}void update(int L,int R,int c,int l,int r,int st){    if(L<=l&&r<=R){        cnt[st]+=c;        push_up(st,l,r);        return ;    }    if(L<=mid)update(L,R,c,lson);    if(R>mid)update(L,R,c,rson);    push_up(st,l,r);}int main(){    int n,tot=1,m;    while(scanf("%d",&n)&&n){        double a,b,c,d,ans=0;        m=0;        while(n--){            scanf("%lf%lf%lf%lf",&a,&b,&c,&d);            x[m]=a;            ss[m++]=Seg(a,c,b,1);            x[m]=c;            ss[m++]=Seg(a,c,d,-1);        }        sort(x,x+m);        sort(ss,ss+m);        for(int i=0;i<m;++i){            int l=lower_bound(x,x+m,ss[i].l)-x;            int r=lower_bound(x,x+m,ss[i].r)-x-1;            update(l,r,ss[i].s,0,m-1,1);            ans+=sum[1]*(ss[i+1].h-ss[i].h);        }        printf("Test case #%d\nTotal explored area: %.2lf\n\n",tot++,ans);    }    return 0;}


0 0