bzoj 2618: [Cqoi2006]凸多边形(半平面交模板)

Description

逆时针给出 n个凸多边形的顶点坐标,求它们交的面积。例如n=2时,两个凸多边形如下图:

则相交部分的面积为5.233。

Input

第一行有一个整数n,表示凸多边形的个数,以下依次描述各个多边形。第i个多边形的第一行包含一个整数mi,表示多边形的边数,以下mi行每行两个整数,逆时针给出各个顶点的坐标。

 

Output

    输出文件仅包含一个实数,表示相交部分的面积,保留三位小数。

 

Sample Input

2
6
-2 0
-1 -2
1 -2
2 0
1 2
-1 2
4
0 -3
1 -1
2 2
-1 0

Sample Output

5.233


半平面交模板 注意去除平行的边(排序时按照位置排序,加入边集时去重)

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<string>
#include<algorithm>
#include<cmath>
using namespace std;
const int Maxn=1005;

inline int read()
{
	char ch=getchar();int i=0,f=1;
	while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
	while(ch>='0'&&ch<='9'){i=(i<<3)+(i<<1)+ch-'0';ch=getchar();}
	return i*f;
}

struct point
{
	double x,y;
	point(double x=0,double y=0):x(x),y(y){}
	friend inline point operator -(const point &a,const point &b)
	{
		return point(a.x-b.x,a.y-b.y);
	}
	friend inline double operator *(const point &a,const point &b)
	{
		return a.x*b.y-a.y*b.x;
	}
}p[Maxn];

struct line
{
	point a,b;
	double slop;
	friend inline bool operator <(const line &a,const line &b)
	{
		if(a.slop!=b.slop) return a.slop<b.slop;
		return (a.b-a.a)*(b.b-a.a)>0;
	}
}l[Maxn],q[Maxn];

inline point inter(line a,line b)
{
	double k1,k2,t;
	k1=(b.b-a.a)*(a.b-a.a);
	k2=(a.b-a.a)*(b.a-a.a); 
	t=k1/(k1+k2);
	point ans;
	ans.x=b.b.x+(b.a.x-b.b.x)*t;
	ans.y=b.b.y+(b.a.y-b.b.y)*t;
	return ans;
}

int n,m,cnt,tot;
double ans;

inline bool judge(line a,line b,line c)
{
	point q=inter(a,b);
	return (c.b-c.a)*(q-c.a)<0;
}
inline void hpi()
{
	sort(l+1,l+cnt+1);
	int L=1,R=0;tot=0;
	for(int i=1;i<=cnt;i++)
	{
		if(l[i].slop!=l[i-1].slop)tot++;
		l[tot]=l[i];
	}
	cnt=tot;tot=0;
	q[++R]=l[1],q[++R]=l[2];
	for(int i=3;i<=cnt;i++)
	{
		while(L<R&&judge(q[R-1],q[R],l[i]))R--;
		while(L<R&&judge(q[L+1],q[L],l[i]))L++;
		q[++R]=l[i];
	}
	while(L<R&&judge(q[L+1],q[L],q[R]))L++;
	while(L<R&&judge(q[R-1],q[R],q[L]))R--;
	q[R+1]=q[L];
	for(int i=L;i<=R;i++)
		p[++tot]=inter(q[i],q[i+1]);
}

inline void getans()
{
	if(tot<3)return;
	p[tot+1]=p[1];
	for(int i=1;i<=tot;i++)
		ans+=p[i]*p[i+1];
	ans=fabs(ans)/2;
}

int main()
{
	n=read();
	while(n--)
	{
		m=read();
		for(int i=1;i<=m;i++)
		p[i].x=read(),p[i].y=read();
		p[m+1]=p[1];
		for(int i=1;i<=m;i++)l[++cnt].a=p[i],l[cnt].b=p[i+1];
	}
	for(int i=1;i<=cnt;i++)
	{
		l[i].slop=atan2(l[i].b.y-l[i].a.y,l[i].b.x-l[i].a.x);
	}
	hpi();
	getans();
	printf("%.3f",ans);
	return 0;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值