HDU1828:Picture

浅谈树状数组与线段树:https://www.cnblogs.com/AKMer/p/9946944.html

题目传送门:http://acm.hdu.edu.cn/showproblem.php?pid=1828

扫描线求周长。如果你不知道什么是扫描线可以先去做这题:https://www.cnblogs.com/AKMer/p/9951300.html

每次扫描线上变化的长度就是周长的一部分。横着做一遍竖着做一遍就行了。

如果两条边(pos)相同应该先加边后删边,否则重叠部分会多算。

时间复杂度:(O(nlogn))

空间复杂度:(O(n))

代码如下:

#include <cmath>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;

const int maxn=10005;

int n;
ll ans;
int tmp[2][maxn];

int read() {
	int x=0,f=1;char ch=getchar();
	for(;ch<'0'||ch>'9';ch=getchar())if(ch=='-')f=-1;
	for(;ch>='0'&&ch<='9';ch=getchar())x=x*10+ch-'0';
	return x*f;
}

struct line {
	int pos,st,ed,mark;

	line() {}

	line(int _pos,int _st,int _ed,int _mark) {
		pos=_pos,st=_st,ed=_ed,mark=_mark;
	}

	bool operator<(const line &a)const {
		if(pos==a.pos)return mark>a.mark;//pos相同优先加边,这样就不会算重叠部分的长度
		return pos<a.pos;
	}
}p[2][maxn];

struct segment_tree {
    int len[maxn<<2],cnt[maxn<<2];

	void clear() {
		memset(len,0,sizeof(len));
		memset(cnt,0,sizeof(cnt));
	}

    void updata(int id,int p,int l,int r) {
        if(cnt[p])len[p]=tmp[id][r+1]-tmp[id][l];
        else if(l==r)len[p]=0;
        else len[p]=len[p<<1]+len[p<<1|1];
    }

    void change(int id,int p,int l,int r,int L,int R,int v) {
        if(L<=l&&r<=R) {
            cnt[p]+=v;
            updata(id,p,l,r);
            return;
        }
        int mid=(l+r)>>1;
        if(L<=mid)change(id,p<<1,l,mid,L,R,v);
        if(R>mid)change(id,p<<1|1,mid+1,r,L,R,v);
        updata(id,p,l,r);
    }
}T;

int main() {
	while(~scanf("%d",&n)) {
		ans=0;
		for(int i=1;i<=n;i++) {
			int x1=read(),y1=read(),x2=read(),y2=read();
			tmp[0][(i<<1)-1]=y1,tmp[0][i<<1]=y2;
			tmp[1][(i<<1)-1]=x1,tmp[1][i<<1]=x2;
			p[0][(i<<1)-1]=line(x1,y1,y2,1);
			p[0][i<<1]=line(x2,y1,y2,-1);
			p[1][(i<<1)-1]=line(y1,x1,x2,1);
			p[1][i<<1]=line(y2,x1,x2,-1);
		}for(int i=0;i<2;i++) {
			T.clear();
			sort(p[i]+1,p[i]+2*n+1);
			sort(tmp[i]+1,tmp[i]+2*n+1);
			int cnt=unique(tmp[i]+1,tmp[i]+2*n+1)-tmp[i]-1;
			for(int j=1;j<=2*n;j++) {
				p[i][j].st=lower_bound(tmp[i]+1,tmp[i]+cnt+1,p[i][j].st)-tmp[i];
				p[i][j].ed=lower_bound(tmp[i]+1,tmp[i]+cnt+1,p[i][j].ed)-tmp[i];
				int tmp=T.len[1];
				T.change(i,1,1,cnt-1,p[i][j].st,p[i][j].ed-1,p[i][j].mark);
				ans+=abs(T.len[1]-tmp);//差值就是周长的一部分
			}
		}
		printf("%lld
",ans);
	}
	return 0;
}
原文地址:https://www.cnblogs.com/AKMer/p/9952402.html