poj1385 求多边形重心

把多边形分割成三角形,对每个三角形求重心,再根据三角形的有向面积为权值求加权平均

#include<cstdio>
#include<cmath>
#define maxl 100010
#define eps 1e-8

inline int sgn(double x)
{
	if(x>-eps && x<eps) return 0;
	if(x>0) return 1;
	else	return -1;
}
struct point
{
	double x,y;
	point(double a=0,double b=0)
	{
		x=a;y=b;
	}
	point operator + (const point &b)const
	{
		return point(x+b.x,y+b.y);
	}
	point operator - (const point &b)const
	{
		return point(x-b.x,y-b.y);
	}
	friend point operator *(const point &b,const double t)
	{
		return point(b.x*t,b.y*t);
	}
	friend point operator *(const double t,const point &b)
	{
		return point(t*b.x,t*b.y);
	}
	friend point operator /(const point &b,const double t)
	{
		return point(b.x/t,b.y/t);
	}
	inline double norm()
	{
		return sqrt(x*x+y*y); 
	} 
};
inline double dot(const point &a,const point &b)
{
	return a.x*b.x+a.y*b.y;
}
inline double det(const point &a,const point &b)
{
	return a.x*b.y-a.y*b.x;
}

struct polygon
{
	int n;
	point a[maxl];
	polygon(){}
	inline double perimeter()
	{
		double sum=0;
		a[n+1]=a[1];
		for(int i=1;i<=n;i++)
			sum+=(a[i+1]-a[i]).norm();
		return sum;
	}
	inline double area()
	{
		double sum=0;
		a[n+1]=a[1];
		for(int i=1;i<=n;i++)
			sum+=det(a[i+1],a[i]);
		return sum/2;
	}
	point get_masscenter()
	{
		point ans=point(0,0);
		if(sgn(area())==0) return ans;//area=0specialjug 
		a[n+1]=a[1];
		for(int i=1;i<=n;i++)
			ans=ans+(a[i]+a[i+1])*det(a[i+1],a[i]);
		return ans/area()/6.;
	}
}d;

int n;
point ans;

inline void prework()
{
	scanf("%d",&d.n);
	for(int i=1;i<=d.n;i++)
		scanf("%lf%lf",&d.a[i].x,&d.a[i].y);
}

inline void mainwork()
{
	ans=d.get_masscenter();
}

inline void print()
{
	if(sgn(ans.x)==0) ans.x=0;
	if(sgn(ans.y)==0) ans.y=0;
	printf("%.2f %.2f\n",ans.x,ans.y);
}

int main()
{
	int t;
	scanf("%d",&t);
	for(int i=1;i<=t;i++)
	{
		prework();
		mainwork();
		print();
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值