HDU 1542 Atlantis

矩形面积并,离散化+线段树

C++ AC,G++ WA,但是数组开大点,G++也AC,不知道为什么

#include<cstdio>
#include<cstring>
#include<cmath>
#include<map>
#include<algorithm>
using namespace std;

const int maxn=2100;
struct Seg
{
    double x;
    int Y1,Y2;//离散化之后的坐标
    int flag;
}s[maxn];
double X1[maxn],X2[maxn],Y1[maxn],Y2[maxn];
map<double ,int>m;
double M[maxn];int k;
int n,tot;
double sum,ans;

struct SegTree
{
    double len;
    int cover;
} segTree[maxn*4];

bool cmp(const Seg&a,const Seg&b)
{
    return a.x<b.x;
}

void lsh()
{
    k=0;
    m.clear();
    for(int i=1; i<=n; i++)
    {
        if(m[Y1[i]]==0) M[k++]=Y1[i],m[Y1[i]]=1;
        if(m[Y2[i]]==0) M[k++]=Y2[i],m[Y2[i]]=1;
    }
    sort(M,M+k);
    m.clear();
    for(int i=0; i<k; i++) m[M[i]]=i;
}

void build(int l,int r,int rt)
{
    segTree[rt].cover=0;
    segTree[rt].len=0;
    if(l==r) return;
    int m=(l+r)/2;
    build(l,m,2*rt);
    build(m+1,r,2*rt+1);
}

void pushUp(int rt,int l,int r)
{
    if(segTree[rt].cover) segTree[rt].len=M[r]-M[l-1];
    else segTree[rt].len=segTree[2*rt].len+segTree[2*rt+1].len;
}

void update(int info,int L,int R,int l,int r,int rt)
{
    if(L<=l&&r<=R)
    {
        segTree[rt].cover=segTree[rt].cover+info;
        pushUp(rt,l,r);
        return;
    }

    int m=(l+r)/2;
    if(L<=m) update(info,L,R,l,m,2*rt);
    if(R>m)  update(info,L,R,m+1,r,2*rt+1);
    pushUp(rt,l,r);
}

int main()
{
    int Case=1;
    while(~scanf("%d",&n))
    {
        if(n==0) break;
        for(int i=1; i<=n; i++)
            scanf("%lf%lf%lf%lf",&X1[i],&Y1[i],&X2[i],&Y2[i]);

        lsh();

        tot=0;
        for(int i=1; i<=n; i++)
        {
            s[tot].x=X1[i],s[tot].Y1=m[Y1[i]],s[tot].Y2=m[Y2[i]],s[tot].flag=1,tot++;
            s[tot].x=X2[i],s[tot].Y1=m[Y1[i]],s[tot].Y2=m[Y2[i]],s[tot].flag=-1,tot++;
        }
        sort(s,s+tot,cmp);

        ans=0;

        build(1,k,1);
        update(s[0].flag,s[0].Y1+1,s[0].Y2,1,k,1);
        for(int i=1; i<tot; i++)
        {
            sum=segTree[1].len;
            ans=ans+sum*(s[i].x-s[i-1].x);
            update(s[i].flag,s[i].Y1+1,s[i].Y2,1,k,1);
        }
        printf("Test case #%d
Total explored area: ",Case++);
        printf("%.2lf

",ans);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/zufezzt/p/5055193.html