hdu 1542(离散化+扫描线)
2015-09-04 22:20
375 查看
题意:给出n个矩形的左下角坐标和右上角坐标,问所有矩形最后并起来的面积。
题解:应该是扫描线的模板题,先离散化横坐标,把所有矩形的上下边存起来(同时存入左右横坐标),按纵坐标从小到大排序,下边标志为1,上边标志为-1,然后从下往上的进行扫描,一旦扫描线扫到某个矩形的下边,对应区间的flag加一,线段树维护的是区间有正数flag标记的长度和,扫描线扫到上边,对应区间flag减一,如果此时flag为0,线段树对应区间覆盖长度被减掉,否则不变。注意这里的flag一定非负,因为从下往上扫描一定下边的数量大于等于上边的数量,也就是1的数量大于等于-1的数量。然后就是这里求线段长度,所以左右区间分别是[left,mid] [mid,right]。
题解:应该是扫描线的模板题,先离散化横坐标,把所有矩形的上下边存起来(同时存入左右横坐标),按纵坐标从小到大排序,下边标志为1,上边标志为-1,然后从下往上的进行扫描,一旦扫描线扫到某个矩形的下边,对应区间的flag加一,线段树维护的是区间有正数flag标记的长度和,扫描线扫到上边,对应区间flag减一,如果此时flag为0,线段树对应区间覆盖长度被减掉,否则不变。注意这里的flag一定非负,因为从下往上扫描一定下边的数量大于等于上边的数量,也就是1的数量大于等于-1的数量。然后就是这里求线段长度,所以左右区间分别是[left,mid] [mid,right]。
#include <cstdio> #include <cstring> #include <algorithm> #include <vector> #include <map> using namespace std; const int N = 205; struct Line { int flag; double lx, rx, h; Line(double a, double b, double c, int d):lx(a), rx(b), h(c), flag(d) {} bool operator < (const Line &a) const { return h < a.h; } }; int n, flag[N << 2]; double tree[N << 2]; vector<double> a; vector<Line> line; map<double, int> mp; void pushup(int k) { tree[k] = tree[k * 2] + tree[k * 2 + 1]; } void modify(int k, int left, int right, int l, int r, int v) { if (left + 1 == right) { flag[k] += v; if (flag[k]) tree[k] = a[right] - a[left]; else tree[k] = 0; return; } int mid = (left + right) / 2; if (l < mid) modify(k * 2, left, mid, l, r, v); if (r > mid) modify(k * 2 + 1, mid, right, l, r, v); pushup(k); } int main() { int cas = 1; while (scanf("%d", &n) == 1 && n) { a.clear(), line.clear(), mp.clear(); memset(flag, 0, sizeof(flag)); memset(tree, 0, sizeof(tree)); double x1, y1, x2, y2; for (int i = 1; i <= n; i++) { scanf("%lf%lf%lf%lf", &x1, &y1, &x2, &y2); line.push_back(Line(x1, x2, y1, 1)); line.push_back(Line(x1, x2, y2, -1)); a.push_back(x1); a.push_back(x2); } sort(line.begin(), line.end()); sort(a.begin(), a.end()); a.erase(unique(a.begin(), a.end()), a.end()); int sz = a.size(), sz2 = line.size(); for (int i = 0; i < sz; i++) mp[a[i]] = i; double res = 0; for (int i = 0; i < sz2; i++) { if (i != 0) res += (line[i].h - line[i - 1].h) * tree[1]; modify(1, 0, sz - 1, mp[line[i].lx], mp[line[i].rx], line[i].flag); } printf("Test case #%d\nTotal explored area: %.2lf\n\n", cas++, res); } return 0; }
相关文章推荐
- LA-3027-Corporative Network-更新深度的并查集
- iOS安全系列之一:HTTPS
- 完美监视你的应用程序--Xamarin洞察
- [leetcode 21] Merge Two Sorted Lists
- swift 学习<六> 闭包练习
- poj 3669 Meteor Shower(bfs)
- 人眼中亮斑的检测、定位和去除
- [LeetCode] H-Index II
- linux命令
- SDK版本大全
- 解决WordPress后台安装主题、插件图片不显示的问题
- .NET基础 (02).NET运行机制
- HDU 4359 Easy Tree DP?
- Caffe学习:build/tools/compute_image_mean
- nodeJS安装(适用于ubuntu和mint系统)
- 员工管理系统
- 应用程序的打包,安装和上传
- STL源码剖析---空间配置器
- Log4j2的flume appender配置
- git update-index --assume-unchanged(忽略已跟踪文件的改动)