参考 博客 http://blog.csdn.net/ysc504/article/details/8812339
这是一道几何题,计算多边形重心。
一个n边形,从一个顶点出发连接其他顶点会得到n-2 个三角形。
因为,除去这个顶点相连接的顶点有n-3个顶点,而n-3条连线分成n-2个三角形。
//①质量集中在顶点上
// n个顶点坐标为(xi,yi),质量为mi,则重心
// X = ∑( xi×mi ) / ∑mi
// Y = ∑( yi×mi ) / ∑mi
// 特殊地,若每个点的质量相同,则
// X = ∑xi / n
// Y = ∑yi / n
//②质量分布均匀
// 特殊地,质量均匀的三角形重心:
// X = ( x0 + x1 + x2 ) / 3
// Y = ( y0 + y1 + y2 ) / 3
//③三角形面积公式:S = ( (x2 - x1) * (y3 - y1) - (x3 - x1) * (y2 - y1) ) / 2 ;
//因此做题步骤:1、将多边形分割成n-2个三角形,根据③公式求每个三角形面积。
// 2、根据②求每个三角形重心。
// 3、根据①求得多边形重心。
#include <iostream>
#include<cstdio>
using namespace std;
struct Point{
double x;
double y;
};
// the x1,y1, x2,y2 x3,y3
// the area is area=[(x2-x1)*(y3-y1)-(x3-x1)*(y2-y1)]/2
double triangleArea(Point p1,Point p2,Point p3){
double area=((p2.x-p1.x)*(p3.y-p1.y)-(p3.x-p1.x)*(p2.y-p1.y))/2.0;
return area;
}
int main()
{
int t;
scanf("%d",&t);
int n;
Point p1,p2,p3;
double fx,fy; //final x final y
double sumArea;
double tmpArea;
while(t--){
fx=fy=sumArea=tmpArea=0;
scanf("%d",&n);
scanf("%lf%lf%lf%lf",&p1.x,&p1.y,&p2.x,&p2.y);
for(int i=2;i<n;i++){
scanf("%lf%lf",&p3.x,&p3.y);
tmpArea=triangleArea(p1,p2,p3);
fx+=(p1.x+p2.x+p3.x)*tmpArea;
fy+=(p1.y+p2.y+p3.y)*tmpArea;
sumArea+=tmpArea;
p2=p3;
}
// must be fx/sumArea then /3.0
fx=fx/3.0/sumArea;
fy=fy/3.0/sumArea;
printf("%.2lf %.2lf\n",fx,fy);
}
return 0;
}