「POJ2954」Triangle
Description
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
1 2 3 |
0 0 1 0 0 1 0 0 5 0 0 5 0 0 0 0 0 0 |
Sample Output
1 2 |
0 6 |
题解
Pick定理:对给定顶点坐标均是整点的简单多边形,其面积A和内部格点数目i、边上格点数目b满足:A=i+b/2-1。
边上的格点数=|dx|和|dy|的最大公约数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
#include<iostream> #include<cstdio> #include<cstring> #include<cmath> using namespace std; int ol,x1,x2,x3,ya,yb,yc; int gcd(int x,int y) {return y==0?x:gcd(y,x%y);} int area() { return abs((x2-x1)*(yc-ya)-(x3-x1)*(yb-ya))/2; } int cal(int x1,int ya,int x2,int yb) { int dx,dy; if(x1<x2)dx=x2-x1;else dx=x1-x2; if(ya<yb)dy=yb-ya;else dy=ya-yb; return gcd(dx,dy); } int main() { while(scanf("%d%d%d%d%d%d",&x1,&ya,&x2,&yb,&x3,&yc)) { if(!x1&&!x2&&!x3&&!ya&&!yb&&!yc)break; ol=cal(x1,ya,x2,yb)+cal(x2,yb,x3,yc)+cal(x3,yc,x1,ya); printf("%d\n",area()-ol/2+1); } return 0; } |