您的位置:首页 > 其它

hdu 1542(离散化+扫描线)

2015-09-04 22:20 375 查看
题意:给出n个矩形的左下角坐标和右上角坐标,问所有矩形最后并起来的面积。

题解:应该是扫描线的模板题,先离散化横坐标,把所有矩形的上下边存起来(同时存入左右横坐标),按纵坐标从小到大排序,下边标志为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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: