hdu 1115(計算多邊形重心)


題意:已知一多邊形沒有邊相交,質量分布均勻。順序給出多邊形的頂點坐標,求其重心。

分析:

求多邊形重心的題目大致有這么幾種:

1,質量集中在頂點上。n個頂點坐標為(xi,yi),質量為mi,則重心
  X = ∑( xi×mi ) / ∑mi
  Y = ∑( yi×mi ) / ∑mi
  特殊地,若每個點的質量相同,則
  X = ∑xi / n
  Y = ∑yi / n

2,質量分布均勻。這個題就是這一類型,算法和上面的不同。
  特殊地,質量均勻的三角形重心:
  X = ( x0 + x1 + x2 ) / 3
  Y = ( y0 + y1 + y2 ) / 3

3,質量分布不均勻。只能用積分來算,不會……

2.7.2 猜想n邊形的重心

猜想由n個點(x1,y1), (x2,y2), ……, (xn,yn)

 

構成的多邊形的重心的坐標是:( ( x1+x2...+xn )/n,( y1+y2+...+yn )/n );

 

v上面公式失效的原因是面積代表的重量並不均勻分布在各個頂點上(如果重量均勻分布在各個頂點上,則上面公式成立)
v可以先求出各個三角形的重心和面積,然后對它們按照權重相加;
 
代碼實現:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#define esp 1e-7

using namespace std;

struct Point{
    double x,y;
    Point(){}
    Point(double x, double y):x(x),y(y){}
    void input()
    {
        scanf("%lf%lf",&x,&y);
    }
};

typedef Point Vector;

Vector operator-(Vector A, Vector B)
{
    return Vector(A.x-B.x, A.y-B.y);
}

double Cross(Vector A, Vector B)
{
    return A.x*B.y-A.y*B.x;
}

double Area(Point A,Point B,Point C)
{
    return Cross(B-A, C-A)/2.0;
}


Point calZhongXing(Point *p, int n)//計算多邊形重心
{
    Point G;
    int i;
    double s,sumS=0;
    G.x=0;G.y=0;
    for(i=1;i<n-1;i++)
    {
        s=Area(p[0], p[i], p[i+1]);
        sumS+=s;
        G.x+=(p[0].x+p[i].x+p[i+1].x)*s;
        G.y+=(p[0].y+p[i].y+p[i+1].y)*s;
    }
    G.x=G.x/sumS/3.0;
    G.y=G.y/sumS/3.0;

    return G;
}

Point a[1000005];

int main()
{
    int T,i,n;
    Point G;
    scanf("%d",&T);
    while(T--)
    {
        
        scanf("%d",&n);
        for(i=0;i<n;i++)
            a[i].input();
        G=calZhongXing(a, n);
        printf("%.2lf %.2lf\n",G.x,G.y);
    }
    return 0;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM