线扫描之面积并

10 篇文章 0 订阅
2 篇文章 0 订阅

#include <cstdio>
#include <map>
#include <algorithm>

using namespace std;
/*代码来自大佬*/
typedef long long ll;

const int kMax = 50000 + 10;

struct P {
    int x, p, v;
    P(int _x = 0, int _p = 0, int _v = 0) : x(_x), p(_p), v(_v) {}
    bool operator < (const P& t) const {
        return x < t.x;
    }
} pos[kMax << 1];

struct node {
    int l, r, times, add;
    ll sum;
} tree[kMax << 3];

int n;
int num[kMax][4], old[kMax << 1];
map<int, int> table;

void pushup(int p) {
    tree[p].times = min(tree[p << 1].times, tree[p << 1 | 1].times);
}

void pushdown(int p) {
    if(tree[p].add) {
        tree[p << 1].times += tree[p].add;
        tree[p << 1 | 1].times += tree[p].add;
        tree[p << 1].add += tree[p].add;
        tree[p << 1 | 1].add += tree[p].add;
        tree[p].add = 0;
    }
}

void build(int p, int l, int r) {
    tree[p].l = l;
    tree[p].r = r;
    tree[p].add = 0;
    tree[p].times = 0;
    tree[p].sum = old[r] - old[l - 1];//一个点代表横坐标其中一段,r=1代表0-1
    if(l == r) return;
    int m = (l + r) >> 1;
    build(p << 1, l, m);
    build(p << 1 | 1, m + 1, r);
}

void update(int p, int l, int r, int v) {
    if(l <= tree[p].l && r >= tree[p].r) {
        tree[p].times += v;
        tree[p].add += v;
        return;
    }
    pushdown(p);
    int m = (tree[p].l + tree[p].r) >> 1;
    if(l <= m) update(p << 1, l, r, v);
    if(r > m) update(p << 1 | 1, l, r, v);
    pushup(p);
}

ll query(int p) {
    if(tree[p].times) return tree[p].sum;
    if(tree[p].l == tree[p].r) return 0;
    pushdown(p);
    return query(p << 1) + query(p << 1 | 1);
}

int main() {
    scanf("%d", &n);//n个矩形
    for(int i = 0;i < n;++ i) {
        for(int j = 0;j < 4;++ j) {
            scanf("%d", &num[i][j]);
            pos[i] = {num[i][1], i, 1};//y1
            pos[n + i] = {num[i][3], i, -1};//y2
            old[i] = num[i][0];//x1
            old[n + i] = num[i][2];//x2
        }
    }
    sort(pos, pos + n * 2);//排序,自下向上扫描
    sort(old, old + n * 2);//排序。方便去重
    int len = unique(old, old + n * 2) - old;//去重
    for(int i = 0;i < len;++ i) {//数据离散化
        table[old[i]] = i + 1;
    }
    build(1, 1, len);//构造线段树
    ll cur = 0, res = 0;
    for(int i = 0;i < n * 2;++ i) {//更新x1至x2,因为table[old[i]] = i + 1,所以r需要-1.比如表示0-10,实际下标是1到10,离散化成1-11了,所以l不变,r-1。篇幅限制没有讲清楚,辅助个人理解而已。
        update(1, table[num[pos[i].p][0]], table[num[pos[i].p][2]] - 1, pos[i].v);
        if(i) res += (pos[i].x - pos[i - 1].x) * cur;//y2-y1乘以上次的长度
        cur = query(1);
    }
    printf("%lld\n", res);//当前长度
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值