hdu 1115 Lifting the Stone

  题目链接:hdu 1115

  计算几何求多边形的重心,弄清算法后就是裸题了,这儿有篇博客写得很不错的: 计算几何-多边形的重心

  代码如下:

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<algorithm>
 4 #include<cmath>
 5 using namespace std;
 6 const int N = 1000006;
 7 
 8 struct point {
 9     double x,y;
10     point() {}
11     point(double x, double y): x(x), y(y) {}
12     void read()  {   scanf("%lf %lf",&x,&y);   }
13     void readint() {
14         int x,y;
15         scanf("%d %d",&x,&y);
16         this->x = x;
17         this->y = y;
18     }
19     point operator - (const point &p2) const {
20         return point(x - p2.x, y - p2.y);
21     }
22 } p[N];
23 
24 typedef point Vector;
25 
26 double cross(Vector a, Vector b) {
27     return a.x * b.y - a.y * b.x;
28 }
29 
30 double Area(point a, point b, point c) {
31     return cross(b - a, c - a) / 2;
32 }
33 
34 inline double center3(double a, double b, double c) {
35     return a + b + c;
36 }
37 
38 int main() {
39     int t,n;
40     scanf("%d",&t);
41     while(t--) {
42         scanf("%d",&n);
43         for(int i = 1; i <= n; ++i)
44             p[i].read();
45 
46         double up = 0, down = 0;
47         point ans;
48         for(int i = 2; i <= n - 1; ++i) {
49             up += center3(p[1].x, p[i].x, p[i + 1].x) * Area(p[1], p[i], p[i + 1]);
50             down += Area(p[1], p[i], p[i + 1]);
51         }
52         ans.x = up / down / 3;
53 
54         up = 0;     down = 0;
55         for(int i = 2; i <= n - 1; ++i) {
56             up += center3(p[1].y, p[i].y, p[i + 1].y) * Area(p[1], p[i], p[i + 1]);
57             down += Area(p[1], p[i], p[i + 1]);
58         }
59         ans.y = up / down / 3;
60         printf("%.2lf %.2lf\n", ans.x, ans.y);
61     }
62     return 0;
63 }

  有个要注意的小细节,对每个小三角形求重心时对最后结果 / 3 即可,而不必在中间过程 / 3,应该是精度问题,所以除法应尽可能避免,因为这题的 n 有点大,所以不断 / 3 操作损失的精度是很大的。

posted @ 2015-09-30 13:30  Newdawn_ALM  阅读(160)  评论(0编辑  收藏  举报