线段树 fzu2187 回家种地

一道很经典的面积并问题。

和普通的面积并相比,这个的面积并求的是只覆盖了一次的答案。


相对于普通的来说,就是求cnt==1的长度,而不是求cnt>=1的长度而已

我的想法是用S1维护cnt>=1的长度,S2维护cnt==1的长度

其他地方和普通的面积并一模一样,只是在push_up的时候稍微多了对S2的维护而已

#include<map>
#include<set>
#include<cmath>
#include<queue>
#include<cstdio>
#include<string>
#include<vector>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<functional>

using namespace std;
typedef long long LL;
typedef pair<int, int> PII;

const int MX = 2e5 + 5;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define root 1,rear,1

int rear, cnt[MX << 2];
int S1[MX << 2], S2[MX << 2], A[MX];

struct Que {
    int sign;
    int top, L, R;
    bool operator<(const Que &b)const {
        return top < b.top;
    }
    Que() {}
    Que(int _top, int _L, int _R, int _sign) {
        top = _top; L = _L; R = _R; sign = _sign;
    }
} Q[MX];

int BS(int x) {
    int l = 1, r = rear, m;
    while(l <= r) {
        m = (l + r) >> 1;
        if(A[m] == x) return m;
        if(A[m] < x)  l = m + 1;
        else        r = m - 1;
    }
    return -1;
}

void push_up(int l, int r, int rt) {
    if(cnt[rt]) {
        S1[rt] = A[r + 1] - A[l];
        if(cnt[rt] == 1) S2[rt] = S1[rt] - S1[rt << 1] - S1[rt << 1 | 1];
        else S2[rt] = 0;
    } else if(l == r) S1[rt] = S2[rt] = 0;
    else {
        S1[rt] = S1[rt << 1] + S1[rt << 1 | 1];
        S2[rt] = S2[rt << 1] + S2[rt << 1 | 1];
    }
}

void update(int L, int R, int d, int l, int r, int rt) {
    if(L <= l && r <= R) {
        cnt[rt] += d;
        push_up(l, r, rt);
        return;
    }

    int m = (l + r) >> 1;
    if(L <= m) update(L, R, d, lson);
    if(R > m) update(L, R, d, rson);
    push_up(l, r, rt);
}

int main() {
    int n, T, ansk = 0;
    //freopen("input.txt", "r", stdin);
    scanf("%d", &T);
    while(T--) {
        rear = 0;
        memset(cnt, 0, sizeof(cnt));
        memset(S1, 0, sizeof(S1));
        memset(S2, 0, sizeof(S2));

        scanf("%d", &n);
        for(int i = 1; i <= n; i++) {
            int x1, y1, x2, y2;
            scanf("%d%d%d%d", &x1, &y1, &x2, &y2);

            A[++rear] = x1, A[++rear] = x2;
            Q[i] = Que(y1, x1, x2, 1);
            Q[i + n] = Que(y2, x1, x2, -1);
        }
        sort(Q + 1, Q + 1 + 2 * n);
        sort(A + 1, A + 1 + rear);
        rear = unique(A + 1, A + 1 + rear) - A - 1;

        LL ans = 0;
        int last = 0;
        for(int i = 1; i <= 2 * n; i++) {
            ans += (LL)(Q[i].top - last) * S2[1];
            update(BS(Q[i].L), BS(Q[i].R) - 1, Q[i].sign, root);
            last = Q[i].top;
        }
        printf("Case %d: %I64d\n", ++ansk, ans);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值