题意:求凸多边形的重心,给出的点不是按照顺序呢排列的,所以要用凸包。
分析:1用Graham扫描算法,就出来了,凸多边形构建完成。
2求重心,把多边形分为多个三角形,求出所有三角形的重心
已知三角形△A1A2A3的顶点坐标Ai ( xi , yi ) ( i =1, 2, 3) 。它的重心坐标为:
xg = (x1+x2+x3) / 3 ; yg = (y1+y2+y3) / 3 ;
定理2 已知三角形△A1A2A3的顶点坐标Ai ( xi , yi ) ( i =1, 2, 3) 。该三角形的面积为:
S = ( (x2 - x1) * (y3 - y1) - (x3 - x1) * (y2 - y1) ) / 2 ;(叉积除以2)
重心=多边形三角剖分的各个三角形的重心*各个三角形的有向面积/多边形面积
#include <iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
using namespace std;
#define N 105
#define EPS 1e-8
struct point
{
double x,y;
point(double x,double y):x(x),y(y){}
point(){}
bool operator< (const point &s)const
{
return x<s.x||(x==s.x&&y<s.y);
}
double det(point a)
{
return x*a.y-y*a.x;
}
point operator-(point a)
{
return point(x-a.x,y-a.y);
}
point operator +(point a)
{
return point(x+a.x,y+a.y);
}
point operator *(double s)
{
return point(x*s,y*s);
}
point operator /(double s)
{
return point(x/s,y/s);
}
};
double area();
point p[N],res[N];
int n,k;
point center_point(double s);
int main()
{
while(~scanf("%d",&n)&&n>=3)
{
for(int i=0;i<n;i++)
{
scanf("%lf%lf",&p[i].x,&p[i].y);
}
sort(p,p+n);
k=0;
for(int i=0;i<n;i++)
{
while(k>1&&(res[k-1]-res[k-2]).det(p[i]-res[k-2])<=0)
k--;
res[k++]=p[i];
}
int t=k;
for(int i=n-2;i>=0;i--)
{
while(k>t&&(res[k-1]-res[k-2]).det(p[i]-res[k-2])<=0)
k--;
res[k++]=p[i];
}
double s=area();
point ans=center_point(s);
printf("%.3f %.3f\n",ans.x,ans.y);
}
return 0;
}
double area()
{
double sum=0;
res[k]=res[0];
for(int i=0;i<k;i++)
{
sum+=res[i].det(res[i+1]);
}
return sum/2;
}
point center_point(double s)
{
point ans=point(0,0);
if(abs(s)<EPS)
return ans;
res[k]=res[0];
for(int i=0;i<k;i++)
{
ans=ans+(res[i]+res[i+1])*res[i].det(res[i+1]);
}
return ans/s/6;
}