HDU 1255 覆盖的面积 线段树+扫描线

本文介绍了一种利用线段树解决二维几何问题的方法。通过处理一系列线段的交点,计算由这些线段围成的区域面积。该算法首先读取输入数据,将线段的端点坐标存储为Line结构体,并对这些坐标进行排序。然后使用线段树维护每个区间的状态,更新区间长度,最后累加得到整个区域的面积。

同 POJ1151 这次是两次

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <stack>
#include <queue>
#include <cmath>
#include <vector>
using namespace std;
const int N=1100;
double y[N<<1];
struct Line
{
    int co;
    double x,y1,y2;
    void fun(double a,double b,double c,int d)
    {
        x=a;
        y1=b;
        y2=c;
        co=d;
    }
    bool operator<(const Line &e)const
    {
        return x<e.x;
    }
}line[N*2];
struct Node
{
    double s,t,len;
    int co;
    void change(int o)
    {
        co+=o;
        if(co<2) len=0;
        else len=t-s;
    }
};
struct Segtree
{
    Node tree[N*8];
    void build(int l,int r,int o)
    {
       tree[o].s=y[l];tree[o].t=y[r];
       tree[o].co=0;tree[o].len=0;
       if(l+1<r)
       {
          int m=(l+r)>>1;
          build(l,m,o*2);
          build(m,r,o*2+1);
       }
    }
    void pushup(int o)
    {
      tree[o].len=tree[o*2].len+tree[o*2+1].len;
    }
    void update(int l,int r,int o,Line e)
    {
        if(l+1==r)
        {
           tree[o].change(e.co);
           return;
        }
        int m=(l+r)>>1;
        if(e.y1<tree[o*2].t)update(l,m,o*2,e);
        if(e.y2>tree[o*2+1].s)update(m,r,o*2+1,e);
        pushup(o);
    }
}seg;
int main()
{
    int n,T;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d",&n);
        int cnt=0;
        for(int i=0;i<n;i++)
        {
            double x1,x2,y1,y2;
            scanf("%lf%lf%lf%lf",&x1,&y1,&x2,&y2);
            line[++cnt].fun(x1,y1,y2,1);
            y[cnt]=y1;
            line[++cnt].fun(x2,y1,y2,-1);
            y[cnt]=y2;
        }
        sort(line+1,line+cnt+1);
        sort(y+1,y+cnt+1);
        int d=1;
        for(int i=2;i<=cnt;i++)
           if(y[i]!=y[i-1])y[++d]=y[i];
        double ans=0;
        seg.build(1,d,1);
        seg.update(1,d,1,line[1]);
        for(int i=2;i<=cnt;i++)
        {
           ans+=(line[i].x-line[i-1].x)*seg.tree[1].len;
           seg.update(1,d,1,line[i]);
        }
        printf("%.2f\n",ans);
    }
    return 0;
}
View Code

 

转载于:https://www.cnblogs.com/shuguangzw/p/5475447.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值