当前位置: 代码迷 >> 综合 >> 线段树 hdu1542 Atlantis
  详细解决方案

线段树 hdu1542 Atlantis

热度:28   发布时间:2023-12-14 03:59:03.0

最经典的一道面积并的问题了。

要注意以下问题:

1.可以按照y的扫描线从小到大排序,然后依次求出每两根扫描线的长度和之间差的距离,得到面积

2.因为坐标值会很大,所以一般把坐标要离散化,然后去重,然后利用二分得到下标

3.假如读入的时候是double类型,然后保存以后其实可以用==去判断是否相等,浮点误差只会在进行过加减乘除以后才会产生

4.因为坐标值是点,然而我们应该按照区间段去编号,所以对于节点l,表示的其实是[l,l+1]这个区间段的长度,这样就将区间段彻底转换成点了

5.因为区间并每次查询的都是整个root,也就是说只要读S[1]就可以了,所以没必要写push_down和query,可以简化很多步骤

6.区间并的push_up比较特殊,,可以仔细瞧瞧

#include<map>
#include<set>
#include<cmath>
#include<stack>
#include<queue>
#include<cstdio>
#include<string>
#include<vector>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<functional>using namespace std;
typedef long long LL;
typedef pair<int, int> PII;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define root 1,rear,1int const MX = 1e3 + 5;int rear, cnt[MX << 2];
double A[MX], S[MX << 2];struct Que {int d;double top, L, R;Que() {}Que(double _top, double _L, double _R, int _d) {top = _top; L = _L; R = _R; d = _d;}bool operator<(const Que &b)const {return top < b.top;}
} Q[MX];int BS(double x) {int L = 1, R = rear, m;while(L <= R) {m = (L + R) >> 1;if(A[m] == x) return m;if(A[m] > x) R = m - 1;else L = m + 1;}return -1;
}void push_up(int l, int r, int rt) {if(cnt[rt]) S[rt] = A[r + 1] - A[l];else if(l == r) S[rt] = 0;else S[rt] = S[rt << 1] + S[rt << 1 | 1];
}void update(int L, int R, int d, int l, int r, int rt) {if(L <= l && r <= R) {cnt[rt] += d;push_up(l, r, rt);return;}int m = (l + r) >> 1;if(L <= m) update(L, R, d, lson);if(R > m) update(L, R, d, rson);push_up(l, r, rt);
}int main() {int n, ansk = 0;//freopen("input.txt", "r", stdin);while(~scanf("%d", &n), n) {rear = 0;memset(cnt, 0, sizeof(cnt));memset(S, 0, sizeof(S));for(int i = 1; i <= n; i++) {double x1, y1, x2, y2;scanf("%lf%lf%lf%lf", &x1, &y1, &x2, &y2);Q[i] = Que(y1, x1, x2, 1);Q[i + n] = Que(y2, x1, x2, -1);A[++rear] = x1; A[++rear] = x2;}sort(Q + 1, Q + 1 + 2 * n);sort(A + 1, A + 1 + rear);rear = unique(A + 1, A + 1 + rear) - A - 1;double ans = 0, last = 0;for(int i = 1; i <= 2 * n; i++) {ans += (Q[i].top - last) * S[1];update(BS(Q[i].L), BS(Q[i].R) - 1, Q[i].d, root);last = Q[i].top;}printf("Test case #%d\n", ++ansk);printf("Total explored area: %.2lf\n\n", ans);}return 0;
}