关闭

Atlantis

245人阅读 评论(0) 收藏 举报
分类:

题目大意:

给出N个矩阵,矩阵会重叠,求矩阵围成的面积

SUCH AS

黑色部分就代表所求的面积。

题目思路:

线段树扫面线,画个图,我们可以把矩阵变成这样一个图形


按照
X轴进行排序,从左到右扫描,将各个不同颜色的长方形进行想家就可以得到答案

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define N 300
#define L(a) a<<1
#define R(a) a<<1|1
#define B(a) printf("***********************%d************************\n",a);

int n;

struct node
{
	int l,r;
	double y1,y2;
	double len;
	int zhuangtai;
}tree[N*4];

struct node2
{
	double x;
	double y1,y2;
	int flag;
	void in(double _x,double _y1,double _y2,int _flag)
	{
		x = _x;
		y1 = _y1;
		y2 = _y2;
		flag = _flag;
	}
}note[N];

double y[N*2];

int cmp(double a,double b)
{
	return a < b; 
}

bool cmp2(node2 a,node2 b)
{
	return a.x < b.x;
} 
void build_tree(int l,int r,int pos)
{
	tree[pos].l = l;
	tree[pos].r = r;
	tree[pos].y1 = y[l];
	tree[pos].y2 = y[r];
	tree[pos].zhuangtai = 0;
	tree[pos].len = 0;
	if( l + 1 == r )
		return ;
	int mid = ( l + r ) >> 1;
	build_tree(l,mid,L(pos));
	build_tree(mid,r,R(pos));
}

void get_len(int pos)
{
	if( tree[pos].zhuangtai > 0 )
		tree[pos].len = tree[pos].y2 - tree[pos].y1;
	else if ( tree[pos].r - tree[pos].l == 1 )
		tree[pos].len = 0;
	else
		tree[pos].len = tree[L(pos)].len + tree[R(pos)].len;
}

void updata(int pos,node2 a)
{
	//cout<<pos<<endl;
	//printf("a.y1 == %.2f a.y2 == %.2f\n",a.y1,a.y2);
	//printf("tree[%d].y1 == %.2f tree[%d].ye == %.2f",pos,tree[pos].y1,pos,tree[pos].y2);
	if( tree[pos].y1 == a.y1 && tree[pos].y2 == a.y2 )
	{
		tree[pos].zhuangtai += a.flag;
		get_len(pos);
		return ;
	}
	
	if( tree[L(pos)].y2 >= a.y2 )
		updata(L(pos),a);
	else if ( tree[R(pos)].y1 <= a.y1 )
		updata(R(pos),a);
	else
	{
		node2 tmp = a;
		tmp.y2 = tree[L(pos)].y2;
		updata(L(pos),tmp);
		tmp = a;
		tmp.y1 = tree[R(pos)].y1;
		updata(R(pos),tmp);
	}
	get_len(pos);
}

int main()
{
	int kas = 1;
	while(scanf("%d",&n)&&n)
	{
		double x1,x2,y1,y2;
		int t = 1;
		for(int i = 0 ; i < n ; i ++ )
		{
			scanf("%lf%lf%lf%lf",&x1,&y1,&x2,&y2);
			note[t].in(x1,y1,y2,1);
			y[t ++] = y1;
			note[t].in(x2,y1,y2,-1);
			y[t ++] = y2;
		}
	//	B(1);
		sort(y+1,y+t,cmp);
		sort(note + 1,note+t,cmp2);
		build_tree(1,t-1,1);
	//	B(2);
	//	for(int i = 1 ; i < t ; i ++ )
	//		printf("y[%d] = %lf\n",i,y[i]);
	//	for(int i = 1 ; i < t ; i ++ )
	//		printf("note[%d].y1 = %lf note[%d].y2 = %lf note[%d].x =%lf\n",i,note[i].y1,i,note[i].y2,i,note[i].x);
		updata(1,note[1]);
		//B(3);
		double sum = 0.0;
		for(int i = 2 ; i < t ; i ++ )
		{
			sum += tree[1].len * ( note[i].x - note[i - 1].x);
			updata(1,note[i]);
		}
	//	B(4);
		printf("Test case #%d\n",kas++);  
        printf("Total explored area: %.2lf\n\n",sum); 
	}
	return 0;
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:6836次
    • 积分:261
    • 等级:
    • 排名:千里之外
    • 原创:18篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条