【HDU】1542 Atlantis 矩形面积并->线段树

http://acm.hdu.edu.cn/showproblem.php?pid=1542

给出n个矩形的左下角和右上角的坐标,求矩形面积的并

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

const int maxn=1005;

int n;
double Y[maxn*2];
struct Line{
    double x;    //横坐标的值
    double y1,y2;//纵坐标区间
    int flag;    //flag==1时表示他是长方形左边;flag==-1时,表示他是长方形右边 
}line[maxn*2];
struct Node{
    double x;    //最新到过该节点的线对应的x
    double left,right;    //左边界、右边界
    bool sign;            //标记该节点是否是叶子节点
    int cover;            //覆盖值 
}node[maxn<<3];
///这里不能使MAXN左移两位,因为有N个矩形,对应2*N个线段,则应该是2*N左移2位。 
bool cmp(struct Line a,struct Line b){
    return a.x<b.x;
}

void Build(int root,int l,int r){
    node[root].left=Y[l];
    node[root].right=Y[r];
    node[root].x=-1;
    node[root].sign=false;   //说明该节点不是叶子节点
    node[root].cover=0;
    if (r-l==1){
        node[root].sign=true; //是叶子节点
        return; 
    }
    int mid=(l+r)>>1;
    Build(root<<1,l,mid);
    Build(root<<1|1,mid,r);
}
///参数含义,root为节点,line_x代表当前线对应的横坐标,l下界,r上界  
///flag代表当前的线是长方形的左侧的边还是右侧的边  
double Calculate(int root,double line_x,double l,double r,int flag){
    if (r<=node[root].left||l>=node[root].right){
        return 0;
    }
    if (node[root].sign){   //如果是叶子节点 
        if (node[root].cover>0){
            double pre=node[root].x;
            double ans=(line_x-pre)*(node[root].right-node[root].left);
            node[root].x=line_x;
            node[root].cover+=flag;
            return ans;
        }
        else{
            node[root].x=line_x;
            node[root].cover+=flag;
            return 0;
        }
    }
    double ans1=Calculate(root<<1,line_x,l,r,flag);
    double ans2=Calculate(root<<1|1,line_x,l,r,flag);
    return ans1+ans2;
}
int main(){

    long long a,b,c,d;
    while (cin >> n && n){
        int num=0;
        for (int i=0;i<n;i++){
            cin >> a >> b >> c >> d;
            Y[num]=b;
            line[num].x=a;
            line[num].y1=b;
            line[num].y2=d;
            line[num].flag=1;
            num++;
            Y[num]=d;
            line[num].x=c;
            line[num].y1=b;
            line[num].y2=d;
            line[num].flag=-1;
            num++;
        }
        sort(Y,Y+num);
        sort(line,line+num,cmp);
        Build(1,0,num-1);
        long long union_area=0;
        for (int i=0;i<num;i++){
            union_area+=Calculate(1,line[i].x,line[i].y1,line[i].y2,line[i].flag);
        }
        cout << union_area << endl;
    }
    cout << "*" << endl;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值