Chinaunix首页 | 论坛 | 博客
  • 博客访问: 7263
  • 博文数量: 4
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 52
  • 用 户 组: 普通用户
  • 注册时间: 2015-04-07 20:52
个人简介

一条狗

文章分类

全部博文(4)

分类: C/C++

2015-05-07 12:00:40

    题目链接:
    要求:计算一块多边形(凹、凸)几何重心
    方法:①将多边形分成(n-2)个三角形;
              ②分别求出(n-2)个三角形的(有向)面积和重心,既 S[i]、centre.x, centre.y,有向面积可保证凹多边形的正负面积相互抵消;
              ③求(n-2)个三角形的重心所组成的多边形的加权重心;
                
    AC要注意的几个地方:
            ①数据要用double类型;
            ②所有除法放到最后进行运算,减少精度损失。

点击(此处)折叠或打开

  1. #include<stdio.h>
  2. #define N 1000008

  3. struct _data
  4. {
  5.     double x;
  6.     double y;

  7.     double area;

  8.     double centre_x;
  9.     double centre_y;
  10. };

  11. struct _data coordinate[N];

  12. double get_area(struct _data a, struct _data b, struct _data c)
  13. {
  14.     double _a_x = b.x - a.x;
  15.     double _a_y = b.y - a.y;

  16.     double _b_x = c.x - a.x;
  17.     double _b_y = c.y - a.y;

  18.     //此处本应是 (_a_x * _b_y - _b_x * _a_y) / 2, 
  19.     //但考虑到在后面的运算中 / 2 会被抵消,所以为减少精度损失,在此将其去掉
  20.     return (_a_x * _b_y - _b_x * _a_y);
  21. }

  22. int main(void)
  23. {
  24.     int T;
  25.     int n;
  26.     struct _data centre;    
  27.     double all_area;

  28.     scanf("%d", &T);
  29.     while(T--)
  30.     {
  31.         centre.x = 0;
  32.         centre.y = 0;

  33.         all_area = 0;

  34.         scanf("%d", &n);
  35.         for(int i = 0; i < n; i++)
  36.         {
  37.             scanf("%lf%lf", &coordinate[i].x, &coordinate[i].y);
  38.         }

  39.         for(int i = 1; i < n - 1; i++)
  40.         {
  41.             coordinate[i].area = get_area(coordinate[0], coordinate[i], coordinate[i+1]);
  42.             all_area += coordinate[i].area;

  43.             coordinate[i].centre_x = (coordinate[0].x + coordinate[i].x + coordinate[i+1].x);
  44.             coordinate[i].centre_y = (coordinate[0].y + coordinate[i].y + coordinate[i+1].y);
  45.         }
  46.     
  47.         for(int i = 1; i < n - 1; i++)
  48.         {
  49.             centre.x += coordinate[i].centre_x * coordinate[i].area;
  50.             centre.y += coordinate[i].centre_y * coordinate[i].area;
  51.         }
  52.     
  53.         centre.x /= all_area * 3;
  54.         centre.y /= all_area * 3;

  55.         //四舍五入
  56.         //centre.x = (int)((centre.x * 100) + 0.5) / 100.0;
  57.         //centre.y = (int)((centre.y * 100) + 0.5) / 100.0;
  58.         printf("%.2lf %.2lf\n", centre.x, centre.y);
  59.     }

  60.     return 0;
  61. }



阅读(298) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~