POJ 1151 Atlantis

~~~题目链接~~~


题目大意:给出每个矩阵的左下角坐标和右上角坐标,求出所有矩阵的面积


思路:在x轴上划分, 在x轴方向求每相邻的两个点所在的矩阵面积。现在的关键就是求每两个点所在的矩形的高如何求, 用线段树来更, 这题最好不要用点树, 叶子节点为区间为1的节点, 这样方便求出y轴上的长度, 看代码吧



#include <stdio.h>
#include <algorithm>
using namespace std;
struct node
{
    double x, y1, y2;
    int k;
    bool operator <(const node &s) const{return x<s.x;}
}p[202];
struct node2
{
    double  w;//w代表当前区间的宽
    int c;//c用来控制更新当前x区间内在y轴的大小, 1表示左边的点, -1表示右边的点, 当为-1时撤除该矩阵的y坐标长度
}t[202*4];
int n = 0, cnt = 1;
double Y[202];

void build(int c, int l, int r)//离散化建树
{
    int m = l+(r-l)/2;
    t[c].w = t[c].c = 0;
    if(l+1 == r) return ;
    build(2*c, l, m);
    build(2*c+1, m, r);
}

void up_data(int c, int l, int r)
{
    if(t[c].c>0)
         t[c].w = Y[r]-Y[l];
    else if(l+1 == r)//根节点, t[c].c == 0时, 更新为0;
         t[c].w = 0;
    else//重新更新, 撤除多余的高度
        t[c].w = t[2*c].w+t[2*c+1].w;
}

void add_x(int c, int l, int r, double lf, double rt, int k)//l, r 为这段的区间, lf, rt为要找的小区间, k为加入的是哪个点(左边的,还是右边的)
{
    int m = l+(r-l)/2;
    if(Y[l]>=lf && Y[r]<=rt)
    {
        t[c].c += k;
        up_data(c, l, r);
        return ;
    }
    if(Y[m]>=rt)//进入左边
        add_x(2*c, l, m, lf, rt, k);
    else if(Y[m]<=lf)
        add_x(2*c+1, m, r, lf, rt, k);
    else
    {
         add_x(2*c, l, m, lf, Y[m], k);
         add_x(2*c+1, m, r, Y[m], rt, k);
    }
    up_data(c, l, r);
}



int main()
{
    int i = 0, cas = 0;
    double ans = 0;
    while(scanf("%d", &n), n)
    {
        cnt = 1;
        ans = 0;
        for(i = 0; i<n; i++)
        {
            double x1, x2, y1, y2;
            scanf("%lf %lf %lf %lf",&x1, &y1, &x2, &y2);
            p[cnt].x = x1;
            p[cnt].y1 = y1;
            p[cnt].y2 = y2;
            p[cnt].k = 1;
            Y[cnt++] = y1;//----------离散化用
            p[cnt].x = x2;
            p[cnt].y1 = y1;
            p[cnt].y2 = y2;
            p[cnt].k = -1;
            Y[cnt++] = y2;
        }
        sort(Y+1, Y+cnt);
        sort(p+1, p+cnt);
        build(1, 1, cnt-1);
        add_x(1, 1, cnt-1, p[1].y1, p[1].y2, p[1].k);
        for(i = 2; i<cnt; i++)
        {
            ans += t[1].w*(p[i].x-p[i-1].x);
            add_x(1, 1, cnt-1, p[i].y1, p[i].y2, p[i].k);
        }
        printf("Test case #%d\n", ++cas);
        printf("Total explored area: %.2lf\n\n", ans);
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值