扫描线

· · 个人记录

非原创

#include<bits/stdc++.h>
#define maxn 105
using namespace std;
int n,tot1,tot2,tot3;
double xa,xb,ya,yb;
double lsh[maxn*2];
double len[maxn*8];
long long sum[maxn*8];
double ans;
struct line{
    double l,r,h;
    int k; 
}l[maxn*2];
bool cmp(line A,line B){
    return A.h<B.h;
}
void update(int u,int L,int R,int l,int r,int k){
    if(l<=L&&R<=r){
        sum[u]+=k;
    }else if(!(R<l||r<L)){
        int M=(L+R)>>1;
        update(u*2,L,M,l,r,k);
        update(u*2+1,M+1,R,l,r,k);
    }
    if(sum[u]){
        len[u]=lsh[R+1]-lsh[L];
    }else{
        if(L==R){
            len[u]=0;
        }else{
            len[u]=len[u*2]+len[u*2+1];
        }
    }
}
int main(){
    ios::sync_with_stdio(0);
    cin.tie(0);cout.tie(0);
    while(scanf("%d",&n)&&n){
        tot1=0,tot2=0,ans=0;
        memset(len,0,sizeof(len));
        memset(sum,0,sizeof(sum));
        for(int i=1;i<=n;i++){
            scanf("%lf %lf %lf %lf",&xa,&ya,&xb,&yb);
            l[++tot1]={xa,xb,ya,1};
            l[++tot1]={xa,xb,yb,-1};
            lsh[++tot2]=xa,lsh[++tot2]=xb;
        }
        sort(l+1,l+1+tot1,cmp);
        sort(lsh+1,lsh+1+tot2);
        tot2=unique(lsh+1,lsh+1+tot2)-lsh-1;
        for(int i=1;i<tot1;i++){
            int L=lower_bound(lsh+1,lsh+1+tot2,l[i].l)-lsh;
            int R=lower_bound(lsh+1,lsh+1+tot2,l[i].r)-lsh;
            update(1,1,tot2,L,R-1,l[i].k);
            ans+=len[1]*(l[i+1].h-l[i].h);
        }
        printf("Test case #%d\nTotal explored area: %.2f\n\n",++tot3,ans);
    }
    return 0;
}