标签:线段树
2 10 10 20 20 15 15 25 25.5 0
Test case #1 Total explored area: 180.00
/*************************************************************************
> File Name: hdu1542.cpp
> Author: ALex
> Mail: 405045132@qq.com
> Created Time: 2015年01月15日 星期四 11时13分38秒
************************************************************************/
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <vector>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 210;
int n, cnt;
struct node
{
double l, r;
double h;
int flag;
}lines[N << 1];
struct seg
{
int l, r;
int add;
double len;
}tree[N << 2];
double xis[N];
int cmp (node a, node b)
{
return a.h < b.h;
}
int BinSearch (double val)
{
int l = 1;
int r = cnt;
int mid;
while (l <= r)
{
mid = (l + r) >> 1;
if (xis[mid] < val)
{
l = mid + 1;
}
else if (xis[mid] > val)
{
r = mid - 1;
}
else
{
break;
}
}
return mid;
}
void build (int p, int l, int r)
{
tree[p].l = l;
tree[p].r = r;
tree[p].len = 0;
tree[p].add = 0;
if (l == r)
{
return;
}
int mid = (l + r) >> 1;
build (p << 1, l, mid);
build (p << 1 | 1, mid + 1, r);
}
void pushup (int p)
{
if (tree[p].add)
{
tree[p].len = xis[tree[p].r + 1] - xis[tree[p].l];
}
else if (tree[p].l == tree[p].r)
{
tree[p].len = 0;
}
else
{
tree[p].len = tree[p << 1].len + tree[p << 1 | 1].len;
}
}
void update (int p, int l, int r, int val)
{
if (l == tree[p].l && r == tree[p].r)
{
tree[p].add += val;
pushup(p);
return;
}
//这里无需down,因为对应每一条直线,插入之后一定有删除操作
int mid = (tree[p].l + tree[p].r) >> 1;
if (r <= mid)
{
update (p << 1, l, r, val);
}
else if (l > mid)
{
update (p << 1 | 1, l, r, val);
}
else
{
update (p << 1, l, mid, val);
update (p << 1 | 1, mid + 1, r, val);
}
pushup (p);
}
int main()
{
int icase = 1;
while (~scanf("%d", &n), n)
{
double x1, y1, x2, y2;
cnt = 0;
for (int i = 1; i <= n; ++i)
{
scanf("%lf%lf%lf%lf", &x1, &y1, &x2, &y2);
lines[i].flag = -1;
lines[i].l = x1;
lines[i].r = x2;
lines[i].h = y2;
xis[++cnt] = x1;
xis[++cnt] = x2;
lines[i + n].l = x1;
lines[i + n].r = x2;
lines[i + n].h = y1;
lines[i + n].flag = 1;
}
sort (lines + 1, lines + 2 * n + 1, cmp);
sort (xis + 1, xis + cnt + 1);
cnt = unique (xis + 1, xis + 1 + cnt) - xis - 1;
double ans = 0;
build (1, 1, cnt);
int l = BinSearch (lines[1].l);
int r = BinSearch (lines[1].r) - 1;
update (1, l, r, lines[1].flag);
for (int i = 2; i <= 2 * n; ++i)
{
ans += tree[1].len * (lines[i].h - lines[i - 1].h);
l = BinSearch (lines[i].l);
r = BinSearch (lines[i].r) - 1;
update (1, l, r, lines[i].flag);
}
printf("Test case #%d\n", icase++);
printf("Total explored area: %.2f\n\n", ans);
}
return 0;
}标签:线段树
原文地址:http://blog.csdn.net/guard_mine/article/details/42741393