POJ 1151 Atlantis 线段树扫描线

题目:http://poj.org/problem?id=1151

题意:给出n个矩形,给出的方式为给出矩形的左下角和右上角两个点,问这些矩形覆盖的面积

思路:线段树扫描线第一题,留个模板

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

const int N = 210;
struct line
{
    double x, y1, y2;
    int f;
}arr[N];
struct node
{
    int l, r, c;
    double len, lf, rf;
}s[N*4];
double y[N];
int n, cas;

bool cmp(line a, line b)
{
    return a.x < b.x;
}
void build(int l, int r, int k)
{
    s[k].l = l, s[k].r = r;
    s[k].c = s[k].len = 0;
    s[k].lf = y[l], s[k].rf = y[r];
    if(l + 1 == r) return;
    int mid = (l + r) >> 1;
    build(l, mid, k << 1);
    build(mid, r, k << 1|1);
}
void cal(int k)
{
    if(s[k].c > 0) s[k].len = s[k].rf - s[k].lf;
    else
    {
        if(s[k].l + 1 == s[k].r) s[k].len = 0;
        else s[k].len = s[k<<1].len + s[k<<1|1].len;
    }
}
void update(line a, int k)
{
    if(a.y1 == s[k].lf && a.y2 == s[k].rf)
    {
        s[k].c += a.f;
        cal(k);
        return;
    }
    if(a.y2 <= s[k<<1].rf) update(a, k << 1);
    else if(a.y1 >= s[k<<1|1].lf) update(a, k << 1|1);
    else
    {
        line tmp = a;
        tmp.y2 = s[k<<1].rf;
        update(tmp, k << 1);
        tmp = a;
        tmp.y1 = s[k<<1|1].lf;
        update(tmp, k << 1|1);
    }
    cal(k);
}
int main()
{
    double x1, y1, x2, y2;
    while(scanf("%d", &n), n)
    {
        int k = 1;
        for(int i = 1; i <= n; i++)
        {
            scanf("%lf%lf%lf%lf", &x1, &y1, &x2, &y2);
            arr[k].x = x1, arr[k].y1 = y1, arr[k].y2 = y2, arr[k].f = 1, y[k++] = y1;
            arr[k].x = x2, arr[k].y1 = y1, arr[k].y2 = y2, arr[k].f = -1, y[k++] = y2;
        }
        sort(arr + 1, arr + k, cmp);
        sort(y + 1, y + k);
        build(1, k - 1, 1);
        update(arr[1], 1);
        double res = 0.0;
        for(int i = 2; i < k; i++)
        {
            res += s[1].len * (arr[i].x - arr[i-1].x);
            update(arr[i], 1);
        }
        printf("Test case #%d\nTotal explored area: %.2f\n\n", ++cas, res);
    }
    return 0;
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值