其他分享
首页 > 其他分享> > POJ 1177/HDU 1828 (线段树+扫描线+求周长,注意有重边的情况)

POJ 1177/HDU 1828 (线段树+扫描线+求周长,注意有重边的情况)

作者:互联网

Sample Input:

7
-15 0 5 10
-5 8 20 25
15 -4 24 14
0 -6 16 4
2 15 10 22
30 10 36 20
34 0 40 16

Sample Output

228
#include<iostream> 
#include<algorithm>
#include<cstring>
#include<cmath>
#define io ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
using namespace std;
const int N=2e5+100;//-----------注意4*N 
using namespace std;
struct Node
{
	double l,r,h;
	int value; 
}a[N];
bool cmp(Node aa,Node bb)
{
	if(aa.h==bb.h)return aa.value>bb.value;
                   //求周长注意这个条件,处理重边 
	return aa.h<bb.h;
}
int Left[N],Right[N],dat[N];//左儿子节点、右儿子节点 
int num[N];
bool flagL[N];
bool flagR[N];

double xx[N],Len[N];//每个节点包含的区间中被覆盖的长度,double型 
void build(int p,int l,int r)
{
	Left[p]=l;
	Right[p]=r;//这个地方总喜欢写成2*p,2*p+1; 
	if(l==r)
	{
		dat[p]=0;
		return ;
	}
	int mid=(l+r)/2;
	build(p*2,l,mid);
	build(p*2+1,mid+1,r);
	dat[p]=0;
}
void pushUp(int p)
{
	if(dat[p])
	{
		num[p]=2;
		flagR[p]=flagL[p]=1;
		Len[p]=xx[Right[p]+1]-xx[Left[p]];
	}
	else
	{
		num[p]=num[2*p]+num[2*p+1];
		flagR[p]=flagR[2*p+1];
		flagL[p]=flagL[2*p];
		Len[p]=Len[p*2]+Len[p*2+1];
		if(flagR[2*p]&&flagL[2*p+1])num[p]-=2;	
	}
}
void change(int p,int l,int r,int v)
{ 
	if(l<=Left[p]&&r>=Right[p])
	{
		dat[p]+=v;//这个点(多个区间)的被覆盖次数,完全覆盖 ,+=v 
		pushUp(p); //被覆盖次数变化,更新自身以及祖先们的Len; 
		return ;
	}
	int mid=(Left[p]+Right[p])/2;
	if(l<=mid)change(p*2,l,r,v);
	if(r>mid)change(p*2+1,l,r,v);
	pushUp(p);//两个change导致子节点被覆盖次数变化,更新p的Len; 
	
}
int main()
{
	io;
	int n;

	while(cin>>n&&n>=0)
	{
		int tot=0;
		int cnt=0;
		memset(Len,0,sizeof(Len));//------guan jian**
		memset(xx,0,sizeof(xx));
		memset(Left,0,sizeof(Left));
		memset(Right,0,sizeof(Right));
		memset(dat,0,sizeof(dat)); 
		
		double sum_s=0;
		for(int i=1;i<=n;++i)
		{
			double x1,y1,x2,y2;
			cin>>x1>>y1>>x2>>y2;//-----注意弄清楚哪两个角 

			a[++tot].l=x1;
			a[tot].r=x2;
			a[tot].h=y1;
			a[tot].value=1;
			//cout<<"tot="<<tot<<",,,,,"<<a[tot].h<<endl;
			a[++tot].l=x1;
			a[tot].r=x2;
			a[tot].h=y2;
			a[tot].value=-1;
			//cout<<"tot="<<tot<<",,,,,, "<<a[tot].h<<endl;
			xx[++cnt]=x1;
			xx[++cnt]=x2;
		}
		sort(xx+1,xx+1+cnt);
		cnt=unique(xx+1,xx+1+cnt)-xx-1;//---------(-xx-1); 
		
//		for(int i=1;i<=cnt;++i)cout<<xx[i]<<" ? ";
//		cout<<endl;
		build(1,1,cnt-1);
                //--------线段树中每个叶子节点表示以该点为左边界的小区间,so:cnt-1 
		sort(a+1,a+1+tot,cmp);

		double ans=0;
		for(int i=1;i<=tot;++i) //i==tot的时候Len【1】==0,去掉tot也可以 
		{
			double tmp=Len[1];
			int x=lower_bound(xx+1,xx+1+cnt,a[i].l)-xx;
			int y=lower_bound(xx+1,xx+1+cnt,a[i].r)-xx;//cout<<i<<endl;

			change(1,x,y-1,a[i].value);	
			ans+=num[1]*(a[i+1].h-a[i].h);
			ans+=fabs(Len[1]-tmp);

		}
		cout<<ans<<endl;
	}
	return 0;
}
/*
2
0 0 4 4
0 4 4 8 
*/ 

 

The end;

 

 

标签:1177,HDU,Right,int,memset,tot,扫描线,sizeof,include
来源: https://blog.csdn.net/qq_41661919/article/details/89906410