线段树扫描线, 离散化
写成notonlysuccess风格爽多了…
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#define ls l, m, rt<<1
#define rs m+1, r, rt<<1|1
#define defm int m = (l+r)>>1
using namespace std;
const int MAXN = 105;
int n, cover[MAXN<<3];
double x1, x2, y1, y2, x[MAXN<<1], len[MAXN<<3];
struct Seg
{
double l, r, h;
int f;
Seg(double ll = 0, double rr = 0, double hh = 0, int ff = 0)
:l(ll), r(rr), h(hh), f(ff) {}
operator<(Seg a) { return h < a.h; }
};
Seg seg[MAXN<<1];
void build(int l, int r, int rt)
{
cover[rt] = 0;
len[rt] = 0;
if(l == r) return;
defm;
build(ls);
build(rs);
}
void pushUp(int l, int r, int rt)
{
if(cover[rt]) len[rt] = x[r+1] - x[l];
else if(l==r) len[rt] = 0;
else len[rt] = len[rt<<1] + len[rt<<1|1];
}
void update(int L, int R, int v, int l, int r, int rt)
{
if(L <= l && r <= R)
{
cover[rt] += v;
pushUp(l, r, rt);
return;
}
if(L > r || l > R) return;
defm;
update(L, R, v, ls);
update(L, R, v, rs);
pushUp(l, r, rt);
}
int main()
{
int cas = 1;
while(scanf("%d", &n) == 1 && n)
{
int cnt = 0;
for(int i=0; i<n; ++i)
{
scanf("%lf%lf%lf%lf", &x1, &y1, &x2, &y2);
seg[cnt] = Seg(x1, x2, y1, 1);
x[cnt++] = x1;
seg[cnt] = Seg(x1, x2, y2, -1);
x[cnt++] = x2;
}
sort(seg, seg+cnt);
sort(x, x+cnt);
int m = unique(x, x+cnt) - x;
build(0, m-1, 1);
double ans = 0;
int l, r;
for(int i=0; i<cnt; ++i)
{
l = lower_bound(x, x+m, seg[i].l) - x;
r = lower_bound(x, x+m, seg[i].r) - x - 1;
update(l, r, seg[i].f, 0, m-1, 1);
ans += (seg[i+1].h - seg[i].h) * len[1];
}
printf("Test case #%d\n", cas++);
printf("Total explored area: %.2f\n\n",ans);
}
return 0;
}
Written with StackEdit.