/*
POJ 1151 Atlantis 求矩形面积并,线段树+扫描线法
http://hi.baidu.com/legend_ni/blog/item/106e9f8a34ff9b04b21bba71.html
线段树经典应用,求矩形并的面积
把每个矩形投影到 x 坐标轴上来(投影到 y 轴上去也是可以的,投影到 x 轴上去的话,就相当于矩形是竖着切的)
然后我们可以枚举矩形的 x 坐标,然后检测当前相邻 x 坐标上 y 方向的合法长度,两种相乘就是面积
然后关键就是如何用线段树来维护那个 “合法长度”
线段树的节点这样定义
struct node { int left,right,cov; double len; }
cov 表示当前节点区间是否被覆盖,len 是当前区间的合法长度
然后我们通过“扫描线”的方法来进行扫描
枚举 x 的竖边,矩形的左边那条竖边就是入边,右边那条就是出边了
然后把所有这些竖边按照 x 坐标递增排序,每次进行插入操作
由于坐标不一定为整数,因此需要进行离散化处理
每次插入时如果当前区间被完全覆盖,那么就要对 cov 域进行更新
入边 +1 出边 -1,更新完毕后判断当前节点的 cov 域是否大于 0
如果大于 0,那么当前节点的 len 域就是节点所覆盖的区间
否则,如果是叶子节点,则 len=0,如果内部节点,则 len=左右儿子的 len 之和
*/
//9379358 NKHelloWorld 1151 Accepted 208K 16MS C++ 2120B 2011-10-01 12:03:02
//9379379 NKHelloWorld 1151 Accepted 208K 16MS C++ 2721B 2011-10-01 12:14:10
#include <algorithm>
#include <iostream>
#include <cstdio>
using namespace std;

#define L(x) ( x << 1 )
#define R(x) ( x << 1 | 1 )

double y[1000];

struct Line
{
 double x, y1, y2;
 int flag;
} line[300];

struct Node
{
 int l, r, cover;
 double lf, rf, len;
} node[1000];

bool cmp ( Line a, Line b )
{
 return a.x < b.x;
}

void length ( int u )
{
 if ( node[u].cover > 0 )
 {
  node[u].len = node[u].rf - node[u].lf;
  return;
 }
 else if ( node[u].l + 1 == node[u].r )
  node[u].len = 0; /* 叶子节点,len 为 0 */
 else
     node[u].len = node[L(u)].len + node[R(u)].len;
}

void build ( int u, int l, int r )
{
 node[u].l = l; node[u].r = r;
 node[u].lf = y[l]; node[u].rf = y[r];
 node[u].len = node[u].cover = 0;
 if ( l + 1 == r ) return;
 int mid = ( l + r ) / 2;
 build ( L(u), l, mid );
 build ( R(u), mid, r );
}

void update ( int u, Line e )
{
 if ( e.y1 == node[u].lf && e.y2 == node[u].rf )
 {
  node[u].cover += e.flag;
  length ( u );
  return;
 }
 if ( e.y1 >= node[R(u)].lf )
  update ( R(u), e );
 else if ( e.y2 <= node[L(u)].rf )
  update ( L(u), e );
 else
 {
  Line temp = e;
  temp.y2 = node[L(u)].rf;
  update ( L(u), temp );
  temp = e;
  temp.y1 = node[R(u)].lf;
  update ( R(u), temp );
 }
 length ( u );
}

int main()
{
 //freopen("a.txt","r",stdin);
 int n, t, i, Case = 0;
 double  x1, y1, x2, y2, ans;
 while ( scanf("%d",&n) && n )
 {
  for ( i = t = 1; i <= n; i++, t++ )
  {
   scanf("%lf%lf%lf%lf",&x1, &y1, &x2, &y2 );
   line[t].x = x1;
   line[t].y1 = y1;
   line[t].y2 = y2;
   line[t].flag = 1;
   y[t] = y1;
   t++;
   line[t].x = x2;
   line[t].y1 = y1;
   line[t].y2 = y2;
   line[t].flag = -1;
   y[t] = y2;
  }

  sort ( line + 1, line + t, cmp );
  sort ( y + 1, y + t );
  build ( 1, 1, t-1 );
        update ( 1, line[1] );

  ans = 0;
  for ( i = 2; i < t; i++ )
  {
   ans += node[1].len * ( line[i].x - line[i-1].x );
   update ( 1, line[i] );
  }
  printf ( "Test case #%d\n", ++Case );
  printf ( "Total explored area: %.2lf\n\n", ans );
 }
 return 0;
}

posted on 2011-10-01 12:34  NKHe!!oWor!d  阅读(610)  评论(0编辑  收藏  举报