luogu3875 [TJOI2010]被污染的河流(矩形面积并,扫描线+线段树)

就是求面积矩形并。wa了好久。我好菜啊。

#include 
#include 
#include 
using namespace std;
#define ll long long
#define inf 0x3f3f3f3f
#define N 100010
inline int read(){
    int x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9') x=x*10+ch-'0',ch=getchar();
    return x*f;
}
int n,num=0;ll ans=0;
struct Lines{
    int x,y1,y2;bool f;
}l[N];
inline bool cmp(Lines x,Lines y){return x.xstruct node{
    int len,clen,cover;
}tree[N<<2];
inline void pushup(int p){
    if(tree[p].cover) return;
    tree[p].clen=tree[p<<1].clen+tree[p<<1|1].clen;
}
inline void build(int p,int l,int r){
    tree[p].len=r-l+1;
    if(l==r) return;int mid=l+r>>1;
    build(p<<1,l,mid);build(p<<1|1,mid+1,r);
}
inline void change(int p,int l,int r,int x,int y,int val){
    if(x<=l&&r<=y){
        tree[p].cover+=val;
        if(tree[p].cover) tree[p].clen=tree[p].len;
        else{
            tree[p].clen=0;if(l!=r) pushup(p);
        }return;
    }
    int mid=l+r>>1;
    if(x<=mid) change(p<<1,l,mid,x,y,val);
    if(y>mid) change(p<<1|1,mid+1,r,x,y,val);
    pushup(p);
}
int main(){
//  freopen("3.in","r",stdin);
    n=read();
    for(int i=1;i<=n;++i){
        int x1=read(),y1=read(),x2=read(),y2=read();
        if(x1==x2){
            if(y1==y2) continue;
            if(y1>y2) swap(y1,y2);x1--;x2++;
            l[++num].x=x1;l[num].y1=y1;l[num].y2=y2;l[num].f=1;
            l[++num].x=x2;l[num].y1=y1;l[num].y2=y2;l[num].f=0;
        }else{
            if(x1>x2) swap(x1,x2);y1--;y2++;
            l[++num].x=x1;l[num].y1=y1;l[num].y2=y2;l[num].f=1;
            l[++num].x=x2;l[num].y1=y1;l[num].y2=y2;l[num].f=0;
        }
    }sort(l+1,l+num+1,cmp);n=100000-1;build(1,0,n);
    for(int i=1;i<=num;++i){
        ans+=(ll)tree[1].clen*(l[i].x-l[i-1].x);
        change(1,0,n,l[i].y1,l[i].y2-1,l[i].f?1:-1);
    }printf("%lld\n",ans);
    return 0;
}

你可能感兴趣的:(其他oj,线段树,扫描线)