码迷,mamicode.com
首页 > 其他好文 > 详细

HDU 1115 Lifting the Stone (求多边形的重心)

时间:2015-08-13 14:33:57      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:

题目链接:传送门

分析:

求多边形的重心的方法:传送门

代码如下:

#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;

const double eps = 1e-10;

struct Point{
    double x,y;
    Point():x(0),y(0){}
    Point(double _x,double _y):x(_x),y(_y){}
};


//判断符号,提高精度
int dcmp(double x){
    if(fabs(x)<eps) return 0;
    else return x < 0 ? -1 : 1;
}


//叉积,可以用来判断方向和求面积
double cross(Point a,Point b,Point c){
    return (a.x-c.x)*(b.y-c.y) - (b.x-c.x)*(a.y-c.y);
}


//求多边形的面积
double S(Point p[],int n){
    double ans = 0;
    for(int i=0;i<n;i++){
        ans+=cross(p[i],p[(i+1)%n],p[(i+2)%n]);
    }
    if(ans<0) ans = -ans;
    return ans/2.0;
}

//求多边形的中心

Point grabity(Point p[],int n){
    Point G;
    double sum_area=0;
    for(int i=2;i<n;i++){
        double area = cross(p[0],p[i-1],p[i]);
        sum_area+=area;
        G.x+=(p[0].x+p[i-1].x+p[i].x)*area;
        G.y+=(p[0].y+p[i-1].y+p[i].y)*area;
    }
    G.x=G.x/3/sum_area,G.y=G.y/3/sum_area;
    return G;
}

Point p[1000010];

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




版权声明:本文为博主原创文章,未经博主允许不得转载。

HDU 1115 Lifting the Stone (求多边形的重心)

标签:

原文地址:http://blog.csdn.net/bigbigship/article/details/47610167

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!