UVA10088多边形内整点个数计算(计算几何)

 1 /*UVA10088
 2 pick定理:
 3 在坐标为整数的二维平面内,对于任意多边形,有s=a+b/2-1,其中b是落在边上的点数,a是内部点数,s是多边形的面积
 4 两个整点连线上的整点的个数是gcd(dx,dy)
 5 You may assume that none of the coordinates will be larger than 1,000,000 in absolute
 6 values.
 7 */
 8 #include <iostream>
 9 #include <cmath>
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <string.h>
13 #define maxn 1010
14 #define LL long long
15 using namespace std;
16 struct Point
17 {
18     double x,y;
19     Point(){}
20     Point(int xx,int yy){x=xx;y=yy;}
21 }P[maxn];
22 typedef Point Vector;
23 //多边形有向面积
24 Vector operator + (Vector A, Vector B)
25 {
26     return Vector(A.x+B.x, A.y+B.y);
27 }
28 //点-点=向量
29 Vector operator - (Vector A, Vector B)
30 {
31 return Vector(A.x-B.x, A.y-B.y);
32 }
33 double Cross(Vector A, Vector B)
34 {
35 return A.x*B.y - A.y*B.x;
36 }
37 double Area2(Point A, Point B, Point C)
38 {
39 return Cross(B-A, C-A);
40 }
41 double PolygonArea(Point *p, int n)
42 {
43 double area = 0.0;
44 for(int i = 1; i < n-1; i++)
45 area += Cross(p[i]-p[0], p[i+1]-p[0]);
46 return area/2.0;
47 }
48 LL gcd(LL a,LL b)
49 {
50 if((a%b)==0) return b;
51 else return gcd(b,a%b);
52 }
53 int n;
54 int main()
55 {
56     while(cin>>n && n>0)
57     {
58         LL b=0;
59         for(int i=0;i<n;i++)
60             cin>>P[i].x>>P[i].y;
61         for(int i=0;i<n;i++)
62         {
63             LL dx=fabs(P[i].x-P[(i+1)%n].x);
64             LL dy=fabs(P[i].y-P[(i+1)%n].y);
65             if(dx>dy)swap(dx,dy);
66             if(dx==0) b+=dy;else if (dy==0) b+=dx;else b+=gcd(dx,dy);//注意实际的dxdy是可能等于0的
67         }
68         double S=fabs(PolygonArea(P,n));
69 //        s=a+b/2-1
70         LL ans=(LL)S+1-(LL)b/2;
71         cout<<ans<<endl;
72     }
73     return 0;
74 }
原文地址:https://www.cnblogs.com/little-w/p/3581510.html