线段树扫描线的模板题,线段树扫描线和线段树区间染色有着相似的地方。它们用线段树维护的都是一段区间,而不是一个结点。
因为扫描线可能需要求带有小数的矩形面积,所以需要离散化。不能简单的用(L,mid)和(mid+1,R)来表示,因为mid和mid+1之间有距离,但是维护一段区间就可以了。
#pragma warning(disable:4996)
#include<iostream>
#include<cstring>
#include<cstdio>
#include<set>
#include<algorithm>
#include<cmath>
#include<climits>
using namespace std;
typedef long long ll;
const int maxn = 1005;
struct node
{
double l, r, h;
int f;
//定义结构体排序,按照高度从下到上排序。
bool operator<(const node& x)const
{
return h < x.h;
}
};
node line[maxn];
double sum[maxn << 2], pos[maxn];
int mark[maxn<<2];
//线段树维护的sum和mark
void pushup(int k, int l, int r)
{
if (mark[k])
{
sum[k] = pos[r+1] - pos[l];
}
else sum[k] = sum[2 * k] + sum[2 * k + 1];
}
void update(int L, int R, int l, int r, int k, int add)
{
if (L <= l && R >= r)
{
mark[k] += add;
pushup(k, l, r);
return;
}
int mid = (l + r) >> 1;
if (L <= mid)update(L, R, l, mid, 2 * k, add);
if (R > mid)update(L, R, mid+1, r, 2 * k + 1, add);
pushup(k, l, r);
}
int main()
{
int i, k, t, L, R, n, m,cas=0;
double x1, x2, y1, y2, ans;
while (scanf("%d", &t) == 1)
{
//多组输入,要置为0
memset(mark, 0, sizeof(mark));
memset(sum, 0, sizeof(sum));
if (t == 0)break;
n = 0, m = 0; ans = 0;
for (i = 1; i <=t; i++)
{
scanf("%lf%lf%lf%lf", &x1, &y1, &x2, &y2);
pos[++n] = x1;
pos[++n] = x2;
line[++m].l = x1;line[m].r = x2;
line[m].h = y1; line[m].f = 1;
line[++m].l = x1; line[m].r = x2;
line[m].h = y2; line[m].f = -1;
}
sort(line + 1, line + 1 + m);
sort(pos + 1, pos + 1 + n);
k = unique(pos + 1, pos + 1 + n) - pos - 1;
for (i = 1; i < n; i++)
{
//二分找出下标
L = lower_bound(pos + 1, pos + 1 + k, line[i].l) - pos;
R = lower_bound(pos + 1, pos + 1 + k, line[i].r) - pos;
//R要减一,因为线段树维护的是一个个区间
R--;
update(L, R, 1, k-1, 1, line[i].f);
ans += sum[1] * (line[i + 1].h - line[i].h);
}
printf("Test case #%d\n", ++cas);
printf("Total explored area: %.2lf\n\n", ans);
}
return 0;
}