【解题报告】POJ1151 扫描线+线段树(矩形求并)

来源:互联网 发布:网络市场监管系统 编辑:程序博客网 时间:2024/06/05 16:27

先贴题目链接吧:http://poj.org/problem?id=1151

今年刚参加完蓝桥杯,第十题就是一道扫描线求矩形面积并的问题,当时还没学习扫描线,有思路但是不会实现,于是花了两天时间好好的学习了一下扫描线。在网上找到了这道,可以说非常经典,也是非常基础的扫描线做法。

先说思路,对于矩形求并问题,最直接的想法肯定是先把所有的面积加起来,然后减去重复的面积。但是这样做,当矩形数量增多,重叠面积会变得极其不好求。那么第二个想法,暴力解决,如果矩形的顶点都是整数,用一个bool判断这个点是否有矩形覆盖,这样的缺点是,会超时,而且局限于顶点为整数。那么扫描线问题是如何解决矩形求并的呢?扫描线其实就是模拟有一条线,从左到右(或从下到上)扫过去,扫到多少面积即多少面积。扫描线算法的复杂度是O(nlgn)。

那么来说说具体是怎么实现的。首先,假设线是从左往右扫的,那么我们可以吧每个矩形竖着的边的x值为分界线,一共有n个矩形,就有2n条竖着的边,分成2n-1个区间。同理横着的边,也可以把y轴分成2n-1个区间。那么扫描线从左往右扫,每扫到一条竖着的边,如果是左边,将其加入当前扫面线的实际长度,然后计算当前x区间的长度乘以扫描线长度。如果是右边,将其剔除扫描线的实际长度,但是要注意,可能会有其他边重叠在上面,所以长度不一定是直接进行加减。因此我们需要用线段树来存取y分出来的区间,每一次将一条边加入线段树,然后进行更新。

接下来贴代码:

#include <iostream>#include <stdio.h>#include <algorithm>using namespace std;#define maxn 201double y[maxn];struct node {int l, r, c;//c为覆盖情况,当前区间有几条竖边覆盖double ly, ry, sum;//sum为扫描线在这个节点所代表的y区间内的长度}tre[maxn << 3];struct line {int  f;//左边为1,右边-1double x, y1, y2;}l[maxn];bool cmp(line x, line y){return x.x < y.x;}void build(int n, int l, int r){tre[n].l = l;tre[n].r = r;tre[n].c = 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){if (tre[n].c>0)tre[n].sum = tre[n].ry - tre[n].ly;else if (tre[n].l + 1 == tre[n].r)tre[n].sum = 0;elsetre[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].c += e.f;calc(n);return;}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, q = 1, t = 1;double ans;double x1, y1, x2, y2;while (cin >> n, n){ans = 0, t = 1;for (int i = 1;i <= n;i++){cin >> 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("Test case #%d\n", q++);printf("Total explored area: %.2f\n\n", ans);//特别需要注意的是poj上.2f能过.2lf就不行了}return 0;}


0 0
原创粉丝点击