覆盖的面积
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 4794 Accepted Submission(s): 2384
Problem Description
给定平面上若干矩形,求出被这些矩形覆盖过至少两次的区域的面积.
![](https://i-blog.csdnimg.cn/blog_migrate/d1adc6253c233d9968f03fe1d872f86d.jpeg)
Input
输入数据的第一行是一个正整数T(1<=T<=100),代表测试数据的数量.每个测试数据的第一行是一个正整数N(1<=N<=1000),代表矩形的数量,然后是N行数据,每一行包含四个浮点数,代表平面上的一个矩形的左上角坐标和右下角坐标,矩形的上下边和X轴平行,左右边和Y轴平行.坐标的范围从0到100000.
注意:本题的输入数据较多,推荐使用scanf读入数据.
注意:本题的输入数据较多,推荐使用scanf读入数据.
Output
对于每组测试数据,请计算出被这些矩形覆盖过至少两次的区域的面积.结果保留两位小数.
Sample Input
2 5 1 1 4 2 1 3 3 7 2 1.5 5 4.5 3.5 1.25 7.5 4 6 3 10 7 3 0 0 1 1 1 0 2 1 2 0 3 1
Sample Output
7.63 0.00求覆盖两次或者以上的面积大小,很明显用扫描线。其实不用线段树也能做出来,但是会TLE~用线段树处理遍历的时候可以达到log(n)。这是我第一次接触这个内容,结合了kuangbin的矩形面积并模板和http://www.cppblog.com/menjitianya/archive/2016/02/25/212891.html这位大神关于线段树的讲解才终于看明白。 这里面都写得很清楚其他的就不多说了,直接上代码。<pre name="code" class="cpp">#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> using namespace std; #define N 2020 #define lson root<<1,l,m #define rson root<<1|1,m,r struct Node { int l,r;//离散化后的区间 int c;//权值 double rl,rr;//有效区间 double once;//覆盖一次及以上的长度 double more;//覆盖两次及以上的长度 } tree[N<<2]; struct Node1 { double x,y1,y2; int c; } line[N<<1]; double y[N]; bool cmp(Node1 a,Node1 b) { return a.x<b.x; } void build(int root,int l,int r) { tree[root].l=l; tree[root].r=r; tree[root].rl=y[l]; tree[root].rr=y[r]; tree[root].once=0; tree[root].more=0; if(l+1==r) return; int m=(l+r)>>1; build(lson); build(rson); } void pushup(int root) { if(tree[root].c>=2) { tree[root].more=tree[root].once=tree[root].rr-tree[root].rl; } else if(tree[root].c==1) { tree[root].once=tree[root].rr-tree[root].rl; if(tree[root].l+1==tree[root].r) { tree[root].more=0; } else { tree[root].more=tree[root<<1].once+tree[root<<1|1].once; } } else { if(tree[root].l+1==tree[root].r) { tree[root].more=tree[root].once=0;//一开始这里忘了分情况一直运行错误,把数组开大了就WA,注意叶子节点没有儿子。 } else { tree[root].more=tree[root<<1].more+tree[root<<1|1].more; tree[root].once=tree[root<<1].once+tree[root<<1|1].once; } } } void update(int root,Node1 a) { if(a.y1==tree[root].rl&&a.y2==tree[root].rr) { tree[root].c+=a.c; pushup(root); return; } if(a.y2<=tree[root<<1].rr) { update(root<<1,a); } else if(a.y1>=tree[root<<1|1].rl) { update(root<<1|1,a); } else { Node1 temp=a; temp.y2=tree[root<<1].rr; update(root<<1,temp); temp=a; temp.y1=tree[root<<1|1].rl; update(root<<1|1,temp); } pushup(root); } int main() { int T; int n; double x1,y1,x2,y2; scanf("%d",&T); int q; while(T--) { q=1; scanf("%d",&n); while(n--) { scanf("%lf %lf %lf %lf",&x1,&y1,&x2,&y2); line[q].x=x1; line[q].y1=y1; line[q].y2=y2; line[q].c=1; y[q++]=y1; line[q].x=x2; line[q].y1=y1; line[q].y2=y2; line[q].c=-1; y[q++]=y2; } sort(line+1,line+q,cmp); sort(y+1,y+q); build(1,1,q-1); update(1,line[1]); double sum=0; for(int i=2; i<q; i++) { sum+=tree[1].more*(line[i].x-line[i-1].x); update(1,line[i]); } printf("%.2lf\n",sum); } return 0; }