Luogu1856 [USACO5.5]矩形周长Picture (线段树扫描线)

对于横轴,加上与上一次扫描的差值;对于竖轴,加上高度差与区间内不相交线段(*2)的积;
难点在pushdown,注意维护覆盖关系。再就注意负数

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#define R(a,b,c) for(register int  a = (b); a <= (c); ++ a)
#define nR(a,b,c) for(register int  a = (b); a >= (c); -- a)
#define Max(a,b) ((a) > (b) ? (a) : (b))
#define Min(a,b) ((a) < (b) ? (a) : (b))
#define Fill(a,b) memset(a, b, sizeof(a))
#define Abs(a) ((a) < 0 ? -(a) : (a))
#define Swap(a,b) a^=b^=a^=b
#define ll long long

#define ON_DEBUG

#ifdef ON_DEBUG

#define D_e_Line printf("

----------

")
#define D_e(x)  cout << #x << " = " << x << endl
#define Pause() system("pause")

#else

#define D_e_Line ;

#endif

struct ios{
    template<typename ATP>ios& operator >> (ATP &x){
        x = 0; int f = 1; char c;
        for(c = getchar(); c < '0' || c > '9'; c = getchar()) if(c == '-')  f = -1;
        while(c >= '0' && c <= '9') x = x * 10 + (c ^ '0'), c = getchar();
        x*= f;
        return *this;
    }
}io;
using namespace std;

#define lson rt << 1, l, mid
#define rson rt << 1 | 1, mid + 1, r

const int N = 20007;

struct Line{
    int l, r, h, tag;
    
    bool operator < (const Line &com)const{
		if(h != com.h) return h < com.h;
		return tag > com.tag;
	}
}a[N];
struct Tree{
    int sum, num, len, ltag, rtag;
}t[N << 2];

inline void Pushdown(int rt, int l, int r){
	if(t[rt].sum){
		t[rt].num = 1;
		t[rt].len = r - l + 1;
		t[rt].ltag = t[rt].rtag = 1;
		return;
	}
	if(l == r){
		t[rt].len = 0;
		t[rt].num = 0;
		t[rt].ltag = t[rt].rtag = 0;
		return;
	}
	t[rt].len = t[rt << 1].len + t[rt << 1 | 1].len;
	t[rt].num = t[rt << 1].num + t[rt << 1 | 1].num;
	if(t[rt << 1].rtag && t[rt << 1 | 1].ltag) --t[rt].num;
	t[rt].ltag = t[rt << 1].ltag;
	t[rt].rtag = t[rt << 1 | 1].rtag;
}
inline void Updata(int rt, int l, int r, int L, int R, int w){
	if(L <= l && r <= R){
		t[rt].sum += w;
		Pushdown(rt, l, r);
		return;
	}
	int mid = (l + r) >> 1;
	if(L <= mid) Updata(lson, L, R, w);
	if(R > mid)  Updata(rson, L, R, w);
	Pushdown(rt, l, r);
}
int main(){
	int n, m = 0;
    io >> n;
    int maxx = 0xcfcfcfcf, minn = 0x7fffffff;
    R(i,1,n){
    	int X1, Y1, X2, Y2;
    	io >> X1 >> Y1 >> X2 >> Y2;
    	maxx = Max(maxx, X2);
    	minn = Min(minn, X1);
        a[++m] = (Line){X1, X2, Y1, 1};
		a[++m] = (Line){X1, X2, Y2, -1};
    }
    if(minn <= 0){
    	R(i,1,m){
    		a[i].l -= minn - 1;
    		a[i].r -= minn - 1;
    	}
    	maxx -= minn - 1;
    }
    sort(a + 1, a + m + 1);
    int ans = 0, last = 0;
    R(i,1,m){
    	Updata(1, 1, maxx, a[i].l, a[i].r - 1, a[i].tag);
    	while(a[i].h == a[i + 1].h && a[i].tag == a[i + 1].tag){
    		++i;
    		Updata(1, 1, maxx, a[i].l, a[i].r - 1, a[i].tag);
    	}
    	ans += Abs(t[1].len - last) + (t[1].num * (a[i + 1].h - a[i].h) << 1);
    	
    	last = t[1].len;    	
    }
    printf("%d
",ans);
    return 0;
}

原文地址:https://www.cnblogs.com/bingoyes/p/11220405.html