Problem
A lattice point is an ordered pair (x, y) where x and y are both integers. Given the coordinates of the vertices of a triangle (which happen to be lattice points), you are to count the number of lattice points which lie completely inside of the triangle (points on the edges or vertices of the triangle do not count).
Input
The input test file will contain multiple test cases. Each input test case consists of six integers x1, y1, x2, y2, x3, and y3, where (x1, y1), (x2, y2), and (x3, y3) are the coordinates of vertices of the triangle. All triangles in the input will be non-degenerate (will have positive area), and -15000 ≤ x1, y1, x2, y2, x3, y3 ≤ 15000. The end-of-file is marked by a test case with x1 = y1 = x2 = y2 = x3 = y3 = 0 and should not be processed.
Output
For each input case, the program should print the number of internal lattice points on a single line.
Sample Input
0 0 1 0 0 1
0 0 5 0 0 5
0 0 0 0 0 0
Sample Output
0
6
思路
此题需要用到如下知识点:
①Pick定理:S=a+b/2-1,其中a表示多边形内部的点数,b表示多边形边界上的点数,s表示多边形的面积;
②三角形面积叉乘公式:S = abs(((x2-x1) * (y3-y1) - (x3-x1) * (y2-y1)) / 2);
③给出两点(x1, y1), (x2, y2),求这两点组成得线段间整数坐标点得个数 b = gcd(abs(x1 - x2),abs(y1 - y2));
代码
#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std;
struct Point{
int x,y;
Point(){};
Point(int _x,int _y):x(_x),y(_y){};
};
int getArea(Point p1,Point p2,Point p3){
int res=(p2.x-p1.x)*(p3.y-p1.y)-(p3.x-p1.x)*(p2.y-p1.y);
if(res<0)res=-res;
return res;
}
int getNum(Point p1,Point p2,Point p3){
int res=__gcd(abs(p1.x-p2.x),abs(p1.y-p2.y));
res+=__gcd(abs(p2.x-p3.x),abs(p2.y-p3.y));
res+=__gcd(abs(p3.x-p1.x),abs(p3.y-p1.y));
return res;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
int x1,x2,x3,y1,y2,y3;
while(cin>>x1>>y1>>x2>>y2>>x3>>y3){
if(x1==0&&x2==0&&x3==0&&y1==0&&y2==0&&y3==0)break;
Point p1(x1,y1),p2(x2,y2),p3(x3,y3);
int area=getArea(p1,p2,p3);
int num=getNum(p1,p2,p3);
cout<<(area-num)/2+1<<endl;
}
return 0;
}