poj 1151(线段树+扫描+几何计算)

本文详细介绍了使用数据结构ST和算法构建、更新、删除操作的实现,针对特定应用需求进行优化,提高了搜索和插入操作的效率。通过排序线段和y坐标数组,采用二叉树结构实现快速定位,最终计算并输出总面积,适用于需要频繁进行搜索、插入和删除操作的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<stdio.h>
#include<algorithm>
#include<iostream>
using namespace std;

struct node
{
	int st,ed,c;
	double m;
}ST[802];

struct line
{
	double x,y1,y2;
	bool s;
}Line[205];

double y[205],ty[205];

void build(int root,int left,int right)
{
	ST[root].st=left;
	ST[root].ed=right;
	ST[root].c=0;
	ST[root].m=0.0;
	
	if(right-left>1)
	{
		int mid=(right+left)/2;
		
		build(2*root,left,mid);
		
		build(2*root+1,mid,right);
	}
}

inline void update(int root)
{
	if(ST[root].c>0)
		ST[root].m=y[ST[root].ed-1]-y[ST[root].st-1];
	else  if(ST[root].ed-ST[root].st==1)
		ST[root].m=0.0;
	else
		ST[root].m=ST[2*root].m+ST[2*root+1].m;
}

void insert(int root,int left,int right)
{
	if(left<=ST[root].st && right>=ST[root].ed)
	{
		ST[root].c++;
		update(root);
		return ;
	}
	if(ST[root].ed-ST[root].st==1) return ;
	int mid=(ST[root].ed+ST[root].st)/2;
	if(left<mid)
		insert(2*root,left,right);    
	if(mid<right)
		insert(2*root+1,left,right);  
	update(root);
}

void Delete(int root,int left,int right)
{
	if(left<=ST[root].st && right>=ST[root].ed)
	{
		ST[root].c--;
		update(root);
		return ;
	}
	if(ST[root].ed-ST[root].st==1) return ;
	int mid=(ST[root].ed+ST[root].st)/2;
	if(left<mid)
		Delete(2*root,left,right);    
	if(mid<right)
		Delete(2*root+1,left,right);  
	update(root);
}

bool cmp(line l1,line l2)
{
	return l1.x<l2.x;
}

int Correspond(int n,double t)
{
	
	int low=0,high=n-1,mid;
	
	while(low<high)
	{
		mid=(low+high)/2;
		
		if(t>y[mid])
			low=mid+1;
		else
			high=mid;
	}
	return high+1;
}
int main()
{
	int n,Case=1;
	int i,num;
	double x1,y1,x2,y2,area;
	
	while(cin>>n,n)
	{
		for(i=0;i<n;i++)
		{
			cin>>x1>>y1>>x2>>y2;
			Line[2*i].x=x1;
			Line[2*i].y1=y1;
			Line[2*i].y2=y2;
			Line[2*i].s=1;
			ty[2*i]=y1;
			Line[2*i+1].x=x2;
			Line[2*i+1].y1=y1;
			Line[2*i+1].y2=y2;
			Line[2*i+1].s=0;
			ty[2*i+1]=y2;
		}
		//for(i=0;i<2*n;i++)
		//  cout<<Line[i].x<<" "<<Line[i].y1<<" "<<Line[i].y2<<" "<<Line[i].s<<endl;
		
		n<<=1;
		sort(Line,Line+n,cmp);
		sort(ty,ty+n);
		y[0]=ty[0];
								
		for(i=num=1;i<n;i++)
		{
			if(ty[i]!=ty[i-1])
				y[num++]=ty[i];
		}
								
		build(1,1,num);
								
		area=0.0;
								
		for(i=0;i<n-1;i++)
		{
			int l=Correspond(num,Line[i].y1);
			int r=Correspond(num,Line[i].y2);
			if(Line[i].s)
			{
				insert(1,l,r);
			}
			else
			{
				Delete(1,l,r);
			}
			area+=ST[1].m*(Line[i+1].x-Line[i].x);
		}
								
		printf("Test case #%d\nTotal explored area: %.2lf\n\n",Case++,area);
	}
	
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值