hdu 1255

本文介绍了一种使用线段树的数据结构来解决二维空间中多个矩形覆盖区域的面积计算问题。通过扫描线算法,结合线段树更新和查询,实现了高效求解。适用于计算机图形学及算法竞赛等领域。
面积并:


#include <iostream>
#include <string.h>
using namespace std;
struct node
{
  int l;
  int r;
  int cover;
  double once;
  double len;
};
node tree[7000];
struct Line
{
   double x;
   double y_down;
   double y_up;
   int cover;
};
Line line[7000];
double yy[7000];
bool cmp(Line a,Line b)
{
    if( a.x == b.x ) 
       return a.cover > b.cover;
    else
       return a.x < b.x;
}
void Build(int i,int l,int r)
{
    tree[i].l = l; 
    tree[i].r = r;
    tree[i].cover = 0;
    tree[i].once = 0.0;
    if(tree[i].l == tree[i].r - 1 )
        return ;
    int mid =(l+r)/2;
    Build(i*2,l,mid);
    Build(i*2+1,mid,r);
}
void fun(int i)
{
    if( tree[i].cover >= 2 )
    {
        tree[i].once = 0;
        tree[i].len = yy[tree[i].r] - yy[tree[i].l];
        return ;
    }
    if( tree[i].cover == 1 )
    {
        if( tree[i].l == tree[i].r - 1 )
            tree[i].len = 0;
        else
            tree[i].len = tree[2*i+1].len + tree[2*i].len + tree[2*i+1].once + tree[2*i].once;
        tree[i].once = yy[tree[i].r] - yy[tree[i].l] - tree[i].len;
        return ;    
    }
    if( tree[i].cover == 0 )
    {
        if( tree[i].l == tree[i].r - 1 )
            tree[i].len =tree[i].once = 0;
        else
        {
            tree[i].len = tree[2*i+1].len + tree[2*i].len;
            tree[i].once =tree[2*i+1].once+tree[2*i].once;
        }
        return ;
    }
}
void Updata(int i, Line p)
{
    if( yy[tree[i].l] >= p.y_down && yy[tree[i].r] <= p.y_up )
    {
        tree[i].cover += p.cover;
        fun(i);
        return ;
    }
    if( tree[i].l == tree[i].r - 1 ) return ;
    int mid = (tree[i].l+tree[i].r)/2;
    if( p.y_down <= yy[mid] )
        Updata(2*i,p);
    if( p.y_up > yy[mid] )
        Updata(2*i+1,p);
    fun(i);
}
int main()
{
    int t,n;
    double x1,x2,y1,y2;
    scanf("%d",&t);
    while( t-- )
    {
        scanf("%d",&n);
        int m = 0;
        for(int i=0; i<n; i++)
        {
            scanf("%lf%lf%lf%lf",&x1,&y1,&x2,&y2);
            line[m].x = x1; 
            line[m].y_down = y1; 
            line[m].y_up = y2;
            line[m].cover = 1;
             yy[m++] = y1;
            line[m].x = x2; 
            line[m].y_down = y1; 
            line[m].y_up = y2;
            line[m].cover = -1;
            yy[m++] = y2;
        }
        sort(yy,yy+m);
        sort(line,line+m,cmp);
        int i = unique(yy,yy+m) - yy;
        Build(1,0,i-1);
        double ans = 0;
        Updata(1,line[0]);
        for(int i=1; i<m; i++)
        {
           ans += tree[1].len*(line[i].x - line[i-1].x);
           Updata(1,line[i]);
        }
        printf("%.2lf\n",ans);
    }

return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值