poj1151 扫描线 矩形面积并

题意:n个矩形求面积并

扫描线算法很容易理解 画一下图就理解了 离散化也不难 一一映射就好 但是把线段放进线段树里维护就很难受了

今天又看了整整一天 并没有理解updata里面几个条件的意思= =

把kuangbin的从左到右扫改成了从下到上 假装自己已经会了= =

#include <cstdio>
#include <algorithm>

using namespace std;
const int N=201;
struct Node{
    double x1,x2,len;
    int lNode,rNode;
    int d;
}segTree[N<<2];
struct Line{
    double y,x1,x2;
    int d;
    bool operator < (const Line&b)const {return y<b.y;}
}line[N<<1];
double x[N<<1];
void build(int t,int l,int r)
{
    segTree[t].x1=x[l];
    segTree[t].x2=x[r];
    segTree[t].lNode=l;
    segTree[t].rNode=r;
    segTree[t].d=segTree[t].len=0;
    if(l+1==r)return;
    int mid=(l+r)>>1;
    build(t<<1,l,mid);
    build(t<<1|1,mid,r);
}
void calen(int t)
{
    if(segTree[t].d)
    {
        segTree[t].len=segTree[t].x2-segTree[t].x1;
    }
    else if(segTree[t].lNode+1==segTree[t].rNode)
    {
        segTree[t].len=0;
    }
    else
    {
        segTree[t].len=segTree[t<<1].len+segTree[t<<1|1].len;
    }
}
void updata(int t,Line e)
{
    if(e.x1==segTree[t].x1&&e.x2==segTree[t].x2)
    {
        segTree[t].d+=e.d;
        calen(t);
        return;
    }
    if(e.x2<=segTree[t<<1].x2)
        updata(t<<1,e);
    else if(e.x1>=segTree[t<<1|1].x1)
        updata(t<<1|1,e);
    else
    {
        Line tmp=e;
        tmp.x2=segTree[t<<1].x2;
        updata(t<<1,tmp);
        tmp=e;
        tmp.x1=segTree[t<<1|1].x1;
        updata(t<<1|1,tmp);
    }
    calen(t);
}
int main()
{
    int n,t,iCase;
    double x1,x2,y1,y2;
    iCase=0;
    while(scanf("%d",&n)&&n)
    {
        t=1;
        for(int i=0;i<n;i++)
        {
            scanf("%lf%lf%lf%lf",&x1,&y1,&x2,&y2);
            x[t]=x1;
            line[t].x1=x1;
            line[t].x2=x2;
            line[t].y=y1;
            line[t].d=1;
            t++;
            x[t]=x2;
            line[t].x1=x1;
            line[t].x2=x2;
            line[t].y=y2;
            line[t].d=-1;
            t++;
        }
        sort(x+1,x+t);
        sort(line+1,line+t);
        build(1,1,t-1);
        updata(1,line[1]);
        double ans=0;
        for(int i=2;i<t;i++)
        {
            ans+=segTree[1].len*(line[i].y-line[i-1].y);
            updata(1,line[i]);
        }
        printf("Test case #%d\nTotal explored area: %.2f\n\n",++iCase,ans);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/yyyccww/article/details/81309099