这道题是紧跟着POJ1151做的,这道题和Atlantis唯一的区别就在于这道题求的是覆盖两次的面积。因为刚刚学习了扫描线,想着如何在原先的模板上进行一些修改来做这道题。我自己的想法是,原先求扫描线实际长度的时候,判断覆盖次数c>0,那么这次只要改为c>1即可。但是在实际操作中遇到了一些困难,因为原先计算的时候,如果线段1的y是从1到5,则我加入线段树的时候只会更新到最大的那个区间,不会一直更新到子区间。但是要计算覆盖了两次的长度,必须把每一个区间都更新。在不改变原先模板结构的情况下,我的做法是记录当前更改的状态,在计算节点存的长度时将其向下传递(有一点lazy的味道,可惜这个是每次都要传递hhh)然后将子节点更新。
PS:我查了查网上的题解,都是增加了一个变量来存当前区间覆盖了两次的长度,他们的题解做法可能比我的做法更优。。但是毕竟是自己想出来的做法,贴出来纪念一下233 毕竟一道题目有多种AC方法嘛
#include
#include
#include
using namespace std;
#define maxn 3001
double y[maxn];
struct node {
int l, r, c;int lazy;
double ly, ry, sum;
}tre[maxn << 3];
struct line {
int f;
double x, y1, y2;
}l[maxn];//左边为1,右边-1
bool cmp(line x, line y)
{
return x.x < y.x;
}
void push_down(int n)
{
tre[n].c += tre[n].lazy;
if (tre[n].l + 1 != tre[n].r)
{
tre[n << 1 | 1].lazy += tre[n].lazy; tre[n << 1].lazy += tre[n].lazy;
}
tre[n].lazy = 0;
}
void build(int n, int l, int r)
{
tre[n].l = l;tre[n].r = r;
tre[n].c = tre[n].lazy = 0;;tre[n].sum = 0;
tre[n].ly = y[l];tre[n].ry = y[r];
if (l + 1 == r)
return;
int mid = (l + r) >> 1;
build(n << 1, l, mid);
build(n << 1 | 1, mid, r);//区间形式为[1,2][2,3],所以是mid
}
void calc(int n)
{
push_down(n);
if (tre[n].c > 1)
tre[n].sum = tre[n].ry - tre[n].ly;
else if (tre[n].l + 1 == tre[n].r)
tre[n].sum = 0;
else
{
calc(n << 1), calc(n << 1 | 1);
tre[n].sum = tre[n << 1].sum + tre[n << 1 | 1].sum;
}
}
void update(int n, line e)
{
if (tre[n].ly == e.y1&&tre[n].ry == e.y2)//找到匹配的区间
tre[n].lazy += e.f;
else if (e.y2 <= tre[n << 1].ry)update(n << 1, e);
else if (e.y1 >= tre[n << 1 | 1].ly)update(n << 1 | 1, e);
else
{
line t = e;
t.y2 = tre[n << 1].ry;
update(n << 1, t);
t = e;
t.y1 = tre[n << 1 | 1].ly;
update(n << 1 | 1, t);
}
calc(n);
}
int main()
{
int n,m, q = 1, t = 1;double ans;
double x1, y1, x2, y2;
scanf("%d", &m);
while (m--)
{
scanf("%d", &n);
ans = 0, t = 1;
for (int i = 1;i <= n;i++)
{
scanf("%lf%lf%lf%lf", &x1, &y1, &x2, &y2);
l[t].x = x1;
l[t].y1 = y1;
l[t].y2 = y2;
l[t].f = 1;
y[t++] = y1;
l[t].x = x2;
l[t].y1 = y1;
l[t].y2 = y2;
l[t].f = -1;
y[t++] = y2;
}
sort(l + 1, l + t, cmp);
sort(y + 1, y + t);
build(1, 1, t - 1);//t-1块区间
update(1, l[1]);//把第一条边放进线段树
for (int i = 2;i < t;i++)
{
ans += tre[1].sum*(l[i].x - l[i - 1].x);//长乘宽
update(1, l[i]);//扫描到第i条线
}
printf("%.2lf\n", ans);
}
return 0;
}