poj 1265

来源:互联网 发布:知乎下载安卓 编辑:程序博客网 时间:2024/06/17 11:33

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))

前提,约定起点不算在该线所经过格点数中。

至此,有如下代码:

[cpp] view plaincopyprint?
  1. #include <iostream>  
  2. #include <stdio.h>  
  3. #include <stdlib.h>  
  4. #include <math.h>  
  5.   
  6. using namespace std;  
  7.   
  8. struct point  
  9. {  
  10.     int x, y;  
  11. };  
  12.   
  13. int gcd(int v1, int v2)  
  14. {  
  15.     while (v2)  
  16.     {  
  17.         int temp = v2;  
  18.         v2 = v1 % v2;  
  19.         v1 = temp;  
  20.     }  
  21.     return v1;  
  22. }  
  23.   
  24. int crossproduct(point a, point b)  
  25. {  
  26.     return a.x * b.y - a.y * b.x;  
  27. }  
  28.   
  29. int main()  
  30. {  
  31.     int n;  
  32.     cin >> n;  
  33.     for (int i = 1; i <= n; i++)  
  34.     {  
  35.         int t;  
  36.         cin >> t;  
  37.   
  38.         point p[105];  
  39.         int Edgepoint = 0;  
  40.         int Innerpoint = 0;  
  41.         int Area = 0;  
  42.   
  43.         p[0].x = 0, p[0].y = 0;  
  44.   
  45.         for (int j = 1; j <= t; j++)  
  46.         {  
  47.             point temp;  
  48.   
  49.             cin >> temp.x >> temp.y;  
  50.             p[j].x = p[j - 1].x + temp.x;  
  51.             p[j].y = p[j - 1].y + temp.y;  
  52.   
  53.             Edgepoint += gcd(abs(temp.x), abs(temp.y));  
  54.             Area += crossproduct(p[j - 1], p[j]);  
  55.         }  
  56.         if (Area < 0) Area = -Area;  
  57.         Innerpoint =(int)( Area / 2 - Edgepoint / 2 + 1 );  
  58.         printf("Scenario #%d:\n%d %d %.1f\n\n", i, Innerpoint, Edgepoint, (double(Area) / 2));  
  59.     }  
  60. }  
0 0
原创粉丝点击