题目链接:https://cn.vjudge.net/problem/HDU-1542
题目大意:求面积并
具体思路:我们首先把矩形分割成一横条一横条的,然后对于每一个我们给定的矩形,我们将储存两个点,一个是左下角,一个是右上角。对于左下角的点,我们将他标记为-1,对于右上角的点,我们把它标记成1,-1代表这块区域的面积是需要减去的,1代表这块区域的面积是需要加上的,然后我们通过扫描线的形式,从y轴从下往上扫就可以了。
离散化的过程,数组还是尽量从0开始吧,因为在更新的过程中会出现0的情况,如果下标从1开始存储的话,会mle的,,,无限递归?
ps:这个线段树的区间分开的时候和之前的不太一样,这个线段树{1,5}分开的是{1,3}和{4,5}
注意这个线段树每一个节点代表的是区间,节点1-3代表的是区间1-4,也就是 节点1代表 区间1-2 ,然后我们查询1-4 的时候,直接查询节点1-3就可以了,更新区间1-3的时候,更新节点1-2就可以了。
AC代码:
1 #include <iostream>
2 #include <cstdio>
3 #include <string>
4 #include <cstring>
5 #include <algorithm>
6 #include <cmath>
7 #include <vector>
8 #include <queue>
9 #include <stack>
10 #include <ctime>
11 #define ll long long
12 # define lson l,m,rt<<1
13 # define rson m+1,r,rt<<1|1
14 using namespace std;
15 const int maxn = 600+100;
16 # define inf 0x3f3f3f3f
17 struct node
18 {
19 double l,r,h;
20 int d;
21 node() {}
22 node(double xx,double yy,double zz,int t)
23 {
24 l=xx;
25 r=yy;
26 h=zz;
27 d=t;
28 }
29 bool friend operator < (node t1,node t2)
30 {
31 return t1.h<t2.h;
32 }
33 } q[maxn];
34 double tree[maxn<<2];
35 double Hash[maxn<<2];
36 int lazy[maxn<<2];
37 void up(int l,int r,int rt)
38 {
39 if(lazy[rt])
40 tree[rt]=Hash[r+1]-Hash[l];//注意这个地方,我们需要计算的是区域,而不是一个点。
41 else if(l==r)
42 tree[rt]=0;
43 else
44 tree[rt]=tree[rt<<1]+tree[rt<<1|1];
45 }
46 void update(int l,int r,int rt,int L,int R,int pos)
47 {
48 if(L<=l&&R>=r)
49 {
50 lazy[rt]+=pos;
51 up(l,r,rt);
52 return ;
53 }
54 int m=(l+r)>>1;
55 if(L<=m)
56 update(lson,L,R,pos);
57 if(R>m)
58 update(rson,L,R,pos);
59 up(l,r,rt);
60 }
61 int main()
62 {
63 int n,Case=0;
64 while(scanf("%d",&n)&&n)
65 {
66 int num=0;
67 double x1,y1,x2,y2;
68 for(int i=1; i<=n; i++)
69 {
70 scanf("%lf %lf %lf %lf",&x1,&y1,&x2,&y2);
71 q[num]= {x1,x2,y1,1};
72 Hash[num++]=x1;
73 q[num]= {x1,x2,y2,-1};
74 Hash[num++]=x2;
75 }
76 sort(Hash,Hash+num);
77 sort(q,q+num);
78 int m=1;
79 for(int i=1; i<num; i++)
80 {
81 if(Hash[i-1]==Hash[i])
82 continue;
83 Hash[m++]=Hash[i];
84 }
85 double ans=0;
86 memset(tree,0,sizeof(tree));
87 memset(lazy,0,sizeof(lazy));
88 for(int i=0; i<num; i++)
89 {
90 int l=lower_bound(Hash,Hash+m,q[i].l)-Hash;
91 int r=lower_bound(Hash,Hash+m,q[i].r)-Hash-1;
92 update(0,m-1,1,l,r,q[i].d);
93 ans+=tree[1]*(q[i+1].h-q[i].h);
94 }
95 printf("Test case #%d\n",++Case);
96 printf("Total explored area: %.2lf\n\n",ans);
97 }
98 return 0;
99 }
来源:https://www.cnblogs.com/letlifestop/p/10332290.html