void-man

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

给出几个矩形的面积,求出相并的总面积....

之前做的感觉都挺水的,现在是线段树的高级点应用了,明显感觉到很难理解了,肿么办啊???慢慢看吧

具体不在这里说了,线段树学习一文里有指出...

#include <queue>
#include <stack>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <limits.h>
#include <string.h>
#include <algorithm>
#define MID(x,y) ((x+y)>>1)
#define L(x) (x<<1)
#define R(x) (x<<1|1)
using namespace std;
const int MAX = 205;
const double eps = 1e-6;
struct rectangle{ double lx,ly,rx,ry;};
struct Rec{double x,y1,y2;int flag;};
struct Tnode{int l,r,cover; double length;};
bool dy(double x,double y)	{	return x > y + eps;}	// x > y
bool xy(double x,double y)	{	return x < y - eps;}	// x < y
bool dyd(double x,double y)	{ 	return x > y - eps;}	// x >= y
bool xyd(double x,double y)	{	return x < y + eps;} 	// x <= y
bool dd(double x,double y) 	{	return fabs( x - y ) < eps;}  // x == y
Tnode node[MAX*4];
Rec rr[MAX];
double y[MAX];
void init()
{
	memset(node,0,sizeof(node));
}
bool cmp(Rec a,Rec b)
{
	return a.x < b.x;
}
void build(int t,int l,int r)
{
	node[t].l = l;
	node[t].r = r;
	if( l == r - 1 ) return ;
	int mid = MID(l,r);
	build(R(t),mid,r);
	build(L(t),l,mid);
}
void len(int t)
{
	if( node[t].cover > 0 )
		node[t].length = y[node[t].r] - y[node[t].l];
	else
		if( node[t].l == node[t].r - 1 )
			node[t].length = 0.0;
		else
			node[t].length = node[R(t)].length + node[L(t)].length;
}
void update(int t,Rec p)
{
	if( y[node[t].l] == p.y1 && y[node[t].r] == p.y2 )
	{
		node[t].cover += p.flag;
		len(t);
		return ;
	}
	int mid = MID(node[t].l,node[t].r);
	if( dyd(p.y1,y[mid]) )
		update(R(t),p);
	else
		if( xyd(p.y2,y[mid]) )
			update(L(t),p);
		else
		{
			Rec tmp = p;
			tmp.y2 = y[mid];
			update(L(t),tmp);
			tmp = p;
			tmp.y1 = y[mid];
			update(R(t),tmp);
		}
	len(t);
}

double solve(int n,int cnt)
{
	init();
	build(1,0,cnt-1);
	double sum = 0.0;
	update(1,rr[0]);
	for(int i=1; i<n; i++)
	{
		sum += (rr[i].x - rr[i-1].x)*node[1].length;
		update(1,rr[i]);
	}
	return sum;
}
int main()
{
	int n;
	int ind = 1;
	double x1,x2,y1,y2;
	while( ~scanf("%d",&n) && n )
	{
		int k = 0;
		for(int i=0; i<n; i++)
		{
			scanf("%lf%lf%lf%lf",&x1,&y1,&x2,&y2);
			rr[k].x = x1; rr[k].y1 = y1;
			rr[k].y2 = y2; rr[k].flag = 1;
			y[k++] = y1;
			rr[k].x = x2; rr[k].y1 = y1;
			rr[k].y2 = y2; rr[k].flag = -1;
			y[k++] = y2;
		}
		sort(rr,rr+k,cmp);
		sort(y,y+k);
		int t = k;
		k = unique(y,y+k) - y;
		double area = solve(t,k);
		printf("Test case #%d\nTotal explored area: %.2lf\n\n",ind++,area);
	}
return 0;
}
posted on 2011-08-07 00:08  void-man  阅读(252)  评论(0)    收藏  举报