版权声明:随意转载,转载请注明出处。 https://blog.csdn.net/qq_36258516/article/details/81540551
POJ 1151|HDU 1542 矩阵面积并
题意
求n个矩形的覆盖面积。
解题思路
扫描线例题。
代码
#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std;
#define lson l, m, rt << 1
#define rson m + 1, r, rt << 1 | 1
const int maxn = 205;
int n;
struct Seg
{
double l, r, h;
int d;
Seg() {}
Seg(double l, double r, double h, int d): l(l), r(r), h(h), d(d) {}
bool operator< (const Seg& rhs) const
{
return h < rhs.h;
}
} arr[maxn];
int cnt[maxn << 2]; //根节点维护的是[l, r+1]的区间
double sum[maxn << 2], all[maxn];
void pushup(int l, int r, int rt)
{
if(cnt[rt]) sum[rt] = all[r + 1] - all[l];
else if(l == r) sum[rt] = 0; //leaves have no sons
else sum[rt] = sum[rt << 1] + sum[rt << 1 | 1];
}
void update(int L, int R, int v, int l, int r, int rt)
{
if(L <= l && R >= r)
{
cnt[rt] += v;
pushup(l, r, rt);
return;
}
int m = l + r >> 1;
if(L <= m) update(L, R, v, lson);
if(R > m) update(L, R, v, rson);
pushup(l, r, rt);
}
int main()
{
#ifdef LOCAL
freopen("in.txt", "r", stdin);
// freopen("out.txt","w",stdout);
#endif
int kase = 0;
while(scanf("%d", &n) == 1 && n)
{
for(int i = 1; i <= n; ++i)
{
double x1, y1, x2, y2;
scanf("%lf%lf%lf%lf", &x1, &y1, &x2, &y2);
arr[i] = Seg(x1, x2, y1, 1);
arr[i + n] = Seg(x1, x2, y2, -1);
all[i] = x1;
all[i + n] = x2;
}
n <<= 1;
sort(arr + 1, arr + 1 + n);
sort(all + 1, all + 1 + n);
int m = unique(all + 1, all + 1 + n) - all - 1;
memset(cnt, 0, sizeof cnt);
memset(sum, 0, sizeof sum);
double ans = 0;
for(int i = 1; i < n; ++i)
{
int l = lower_bound(all + 1, all + 1 + m, arr[i].l) - all;
int r = lower_bound(all + 1, all + 1 + m, arr[i].r) - all;
update(l, r - 1, arr[i].d, 1, m-1, 1);
ans += sum[1] * (arr[i + 1].h - arr[i].h);
}
printf("Test case #%d\nTotal explored area: %.2f\n\n", ++kase, ans);
}
return 0;
}