http://poj.org/problem?id=1265
Pick定理:一个计算点阵中顶点在格点上的多边形面积公式:S=a+b÷2-1,其中a表示多边形内部的点数,b表示多边形边界上的点数,s表示多边形的面积。
如图:
图中是样例二。题目要求输出边界格点个数、内部格点个数、其面积。已知一条直线,如图中(5,0)到(6,3)这条直线,经过的整点数是2,可通过如下公式计算:
格点数 = gcd(abs(x2-x1),abs(y2-y1))
前提,约定起点不算在该线所经过格点数中。
至此,有如下代码:
- #include <iostream>
- #include <stdio.h>
- #include <stdlib.h>
- #include <math.h>
- using namespace std;
- struct point
- {
- int x, y;
- };
- int gcd(int v1, int v2)
- {
- while (v2)
- {
- int temp = v2;
- v2 = v1 % v2;
- v1 = temp;
- }
- return v1;
- }
- int crossproduct(point a, point b)
- {
- return a.x * b.y - a.y * b.x;
- }
- int main()
- {
- int n;
- cin >> n;
- for (int i = 1; i <= n; i++)
- {
- int t;
- cin >> t;
- point p[105];
- int Edgepoint = 0;
- int Innerpoint = 0;
- int Area = 0;
- p[0].x = 0, p[0].y = 0;
- for (int j = 1; j <= t; j++)
- {
- point temp;
- cin >> temp.x >> temp.y;
- p[j].x = p[j - 1].x + temp.x;
- p[j].y = p[j - 1].y + temp.y;
- Edgepoint += gcd(abs(temp.x), abs(temp.y));
- Area += crossproduct(p[j - 1], p[j]);
- }
- if (Area < 0) Area = -Area;
- Innerpoint =(int)( Area / 2 - Edgepoint / 2 + 1 );
- printf("Scenario #%d:\n%d %d %.1f\n\n", i, Innerpoint, Edgepoint, (double(Area) / 2));
- }
- }

本文介绍了一个利用Pick定理计算点阵中多边形面积的C++实现方法,并通过具体实例展示了如何计算边界上的整点数及多边形的面积。
2625

被折叠的 条评论
为什么被折叠?



