Center of Masses UVA - 10002

计算多边形的重心

借鉴大佬的公式:

每个三角形重心:cx = x1 + x2 + x3;cy同理。
每个三角形面积:s =  ( (x2 - x1) * (y3 - y1) - (x3 - x1) * (y2 - y1) ) / 2;

多边形重心:cx = (∑ cx[i]*s[i]) / (3*∑s[i]);  cy = (∑ cy[i]*s[i] ) / (3*∑s[i]);

#include <iostream>
#include <cmath>
#include <cstdio>
#include <algorithm>


using namespace std;

const int maxn=200;
const double eps=1e-8;


int sgn(double x)
{
    if(fabs(x)<eps)
        return 0;
    if(x<0)
        return -1;
    else
        return 1;
}
struct Point
{
    double x,y;
    Point(){}
    Point(double _x,double _y)
    {
        x=_x;
        y=_y;
    }
    Point operator -(const Point &b)const
    {
        return Point(x-b.x,y-b.y);
    }
    double operator ^(const Point &b)const
    {
        return x*b.y-y*b.x;
    }
    double operator *(const Point &b)const
    {
        return x*b.x+y*b.y;
    }
};

Point p[maxn];
int n;
int Stack[maxn];
int top;

double dist(Point a,Point b)
{
    return sqrt((a-b)*(a-b));
}
bool cmp(Point a,Point b)
{
    int ans=sgn((a-p[0])^(b-p[0]));
    if(ans==1)
        return true;
    else if(ans==0)
        return dist(a,p[0])<dist(b,p[0]);
    else
        return false;
}

void graham()
{
    for(int i=0;i<n;i++)
    {
        if(p[i].y<p[0].y||(p[i].y==p[0].y&&p[i].x<p[0].x))
            swap(p[i],p[0]);
    }
    sort(p+1,p+n,cmp);
    Stack[0]=0;
    Stack[1]=1;
    top=2;
    for(int i=2;i<n;i++)
    {
        while(top>1&&sgn((p[Stack[top-1]]-p[Stack[top-2]])^(p[i]-p[Stack[top-2]]))<=0)
            top--;
        Stack[top++]=i;
    }
}

Point center_of_masses(Point p[],int n)
{
    double s=0;
    double cx=0;
    double cy=0;
    Point p1=Point(0,0);
    for(int i=0;i<n;i++)
    {
        double s1;
        double x;
        double y;
        int ans=sgn(((p[i]-p1)^(p[(i+1)%n])));
        if(ans==0)
            s1=0;
        else
            s1=((p[i]-p1)^(p[(i+1)%n]))/2.0;
        x=(0+p[i].x+p[(i+1)%n].x);
        y=(0+p[i].y+p[(i+1)%n].y);
        cx+=s1*x;
        cy+=s1*y;
        s+=s1;
    }
    s=fabs(s);
    return Point(cx/s/3.0,cy/s/3.0);
}
Point p1[maxn];
int main()
{
    while(1)
    {
        cin>>n;
        if(n<3)
            break;
        for(int i=0;i<n;i++)
        {
            scanf("%lf %lf",&p[i].x,&p[i].y);
        }
        graham();
        /*for(int i=0;i<top;i++)
            cout<<p[Stack[i]].x<<" "<<p[Stack[i]].y<<endl;*/
        for(int i=0;i<top;i++)
            p1[i]=p[Stack[i]];
        Point ans=center_of_masses(p1,top);
        printf("%.3lf %.3lf\n",ans.x,ans.y);
    }
    return 0;
}

 

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/leekerian/article/details/81592974
个人分类: ACM
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭