hdu 1542 Atlantis(矩形面积并)

来源:互联网 发布:cf一键领枪软件 编辑:程序博客网 时间:2024/05/21 06:36
题目:http://acm.hdu.edu.cn/showproblem.php?pid=1542
题目大意:给你n个矩形,每个矩形由左下角和右上角两个点来确定,让你求出这n个矩形的面积并。
思路:线段树扫描线的基础题,唯一要注意的是这里我们往线段树里加线段时,要注意是左闭右开的,就是这里r的 -1,+1。

代码如下:

#include<cstdio>#include<cstring>#include<algorithm>using namespace std;#define lson rt<<1,l,mid#define rson rt<<1|1,mid+1,rconst int MAXN = 222;struct Line{    double l,r,h;    int flag;    Line(){}    Line(double a,double b,double c,int d)    {        l = a;        r = b;        h = c;        flag = d;    }    bool operator < (const Line &tmp) const    {        return h < tmp.h;    }} line[MAXN];double x[MAXN];int Bin(int l,int r,double key){    while(l <= r)    {        int mid = (l+r)>>1;        if(x[mid] == key)        {            return mid;        }        else if(x[mid] < key)            l = mid+1;        else r = mid-1;    }    return -1;}double sum[MAXN<<2];int cnt[MAXN<<2];void push_up(int rt,int l,int r){    if(cnt[rt]) sum[rt] = x[r+1]-x[l];    else if(l == r) sum[rt] = 0;    else sum[rt] = sum[rt<<1]+sum[rt<<1|1];}void update(int rt,int l,int r,int a,int b,int c){    if(a <= l && b >= r)    {        cnt[rt] += c;        push_up(rt,l,r);        return ;    }    int mid = l+r>>1;    if(a <= mid) update(lson,a,b,c);    if(b > mid) update(rson,a,b,c);    push_up(rt,l,r);}void build(int rt,int l,int r){    cnt[rt] = sum[rt] = 0;    if(l == r)        return ;    int mid = l+r>>1;    build(lson);    build(rson);}int main(){    int cas = 0;    int n;    while(~scanf("%d",&n) && n)    {        double a,b,c,d;        int tot = 0;        for(int i = 0;i < n;i++)        {            scanf("%lf%lf%lf%lf",&a,&b,&c,&d);            x[tot] = a;            line[tot++] = Line(a,c,b,1);            x[tot] = c;            line[tot++] = Line(a,c,d,-1);        }        sort(x,x+tot);        sort(line,line+tot);        int m = unique(x,x+tot)-x;        build(1,0,m-1);        double ans = 0;        for(int i = 0;i < tot-1;i++)        {            int l = Bin(0,m-1,line[i].l);            int r = Bin(0,m-1,line[i].r);            //printf("l = %d,r = %d,m = %d\n",l,r,m);            update(1,0,m-1,l,r-1,line[i].flag);            ans += sum[1]*(line[i+1].h-line[i].h);            //printf("sum1 = %lf,ans = %lf\n",sum[1],ans);        }        printf("Test case #%d\n",++cas);        printf("Total explored area: %.2f\n\n",ans);    }    return 0;}


原创粉丝点击