当前位置: 代码迷 >> 综合 >> HDU 1255 覆盖的面积(矩形交的面积)
  详细解决方案

HDU 1255 覆盖的面积(矩形交的面积)

热度:34   发布时间:2023-12-08 11:09:18.0

题目链接:
HDU 1255 覆盖的面积

//1832K 280MS
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <climits>
#define lson(x) (x<<1)
#define rson(x) ((x<<1)|1)
using namespace std;const int maxn=5050;int T,n;
double x1,x2,yy1,y2,xx[maxn<<2];struct SegTree{int left,right,flag;double len1,len2;//len1是覆盖一次的长度,len2是覆盖不止一次的长度
}segtree[maxn<<4];struct Line{double x1,x2,y;int flag;bool operator < (const Line a) const{return y<a.y;}
}line[maxn<<2];inline void build(int left,int right,int cur)
{segtree[cur].left=left;segtree[cur].right=right;segtree[cur].flag=0;segtree[cur].len1=segtree[cur].len2=0;if(left+1==right) return ;int mid=(left+right)>>1;build(left,mid,lson(cur));build(mid,right,rson(cur));
}inline void calc_len(int cur)
{int left=segtree[cur].left;int right=segtree[cur].right;if(segtree[cur].flag>0) segtree[cur].len1=xx[right]-xx[left];else if(left+1==right) segtree[cur].len1=0;else segtree[cur].len1=segtree[lson(cur)].len1+segtree[rson(cur)].len1;//flag>1说明整个区间有不止一次覆盖,flag=1说明整个区间是完全覆盖,//但是在这个区间下可能有小区间之前已经被完全覆盖了,所以要加上子树中被覆盖一次的的区间长度//flag<1那么就是左右子树覆盖两次长度之和if(segtree[cur].flag>1) segtree[cur].len2=xx[right]-xx[left];else if(left+1==right) segtree[cur].len2=0;//叶子结点且flag<=1,则覆盖两次的长度只能是0else if(segtree[cur].flag==1)segtree[cur].len2=segtree[lson(cur)].len1+segtree[rson(cur)].len1;else segtree[cur].len2=segtree[lson(cur)].len2+segtree[rson(cur)].len2;return;
}inline void update(int a,int b,int flag,int cur)
{int left=segtree[cur].left;int right=segtree[cur].right;if(left==a&&right==b){segtree[cur].flag+=flag;calc_len(cur);return;}int mid=(left+right)>>1;if(b<=mid) update(a,b,flag,lson(cur));else if(a>=mid) update(a,b,flag,rson(cur));else{update(a,mid,flag,lson(cur));update(mid,b,flag,rson(cur));}calc_len(cur);
}int main()
{
#ifdef LOCALfreopen("in.txt","r",stdin);
#endifscanf("%d",&T);while(T--){scanf("%d",&n);int tot=0;for(int i=0;i<n;i++){scanf("%lf %lf %lf %lf",&x1,&yy1,&x2,&y2);line[tot].x1=x1,line[tot].x2=x2,line[tot].y=yy1,line[tot].flag=1;line[tot+1].x1=x1,line[tot+1].x2=x2,line[tot+1].y=y2,line[tot+1].flag=-1;xx[tot]=x1,xx[tot+1]=x2;tot+=2;}sort(xx,xx+tot);int m=unique(xx,xx+tot)-xx;build(0,m-1,1);sort(line,line+tot);double ans=0;int a,b;for(int i=0;i<tot-1;i++){a=lower_bound(xx,xx+m,line[i].x1)-xx;b=lower_bound(xx,xx+m,line[i].x2)-xx;update(a,b,line[i].flag,1);//printf("i=%d len=%.2f\n",i,segtree[1].len2);ans+=segtree[1].len2*(line[i+1].y-line[i].y);}printf("%.2f\n",ans);}return 0;
}