http://acm.hdu.edu.cn/showproblem.php?pid=1542
There are several ancient Greek texts that contain descriptions of the fabled island Atlantis. Some of these texts even include maps of parts of the island. But unfortunately, these maps describe different regions of Atlantis. Your friend Bill has to know the total area for which maps exist. You (unwisely) volunteered to write a program that calculates this quantity
计算给出的n个矩形的总面积
简单计算面积,注意double离散化
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
const int maxn = 2000 + 3;
vector<double> hsh;
int getid(double x) {
return lower_bound(hsh.begin(), hsh.end(), x) - hsh.begin();
}
struct node {
double l, r, h;
int flg;
node() {}
node(double _l, double _r, double _h, int _flg) : l(_l), r(_r), h(_h), flg(_flg) {}
bool operator <(const node& x) const {
return h < x.h;
}
} E[maxn << 1];
struct SegementTree {
int s;
double len;
} tre[maxn << 2];
void build(int rt, int l, int r) {
tre[rt].s = tre[rt].len = 0;
if(l == r) return;
int mid = l + r >> 1;
build(rt << 1, l, mid);
build(rt << 1 | 1, mid + 1, r);
}
void pushup(int rt, int l, int r) {
if(tre[rt].s)
tre[rt].len = hsh[r + 1] - hsh[l];
else if(l == r)
tre[rt].len = 0;
else
tre[rt].len = tre[rt << 1].len + tre[rt << 1 | 1].len;
}
void update(int rt, int L, int R, int val, int l, int r) {
if(L <= l && r <= R) {
tre[rt].s += val;
pushup(rt, l, r);
return;
}
int mid = l + r >> 1;
if(mid >= R) update(rt << 1, L, R, val, l, mid);
else if(mid < L) update(rt << 1 | 1, L, R, val, mid + 1, r);
else update(rt << 1, L, R, val, l, mid), update(rt << 1 | 1, L, R, val, mid + 1, r);
pushup(rt, l, r);
}
int main()
{
int n, cas = 1;
while(~scanf("%d", &n)) {
if(n == 0) break;
hsh.clear();
int tot = 0;
double x1, y1, x2, y2;
for(int i = 0; i < n; ++i) {
scanf("%lf%lf%lf%lf", &x1, &y1, &x2, &y2);
hsh.push_back(x1);
hsh.push_back(x2);
E[tot++] = node(x1, x2, y1, 1);
E[tot++] = node(x1, x2, y2, -1);
}
sort(hsh.begin(), hsh.end());
hsh.erase(unique(hsh.begin(), hsh.end()), hsh.end());
sort(E, E + tot);
build(1, 0, hsh.size() - 1);
double ans = 0;
for(int i = 0; i < tot; ++i) {
update(1, getid(E[i].l), getid(E[i].r) - 1, E[i].flg, 0, hsh.size() - 1);
ans += tre[1].len * (E[i + 1].h - E[i].h);
}
printf("Test case #%d\nTotal explored area: %.2f\n\n", cas++, ans);
}
}