POJ 2954 Triangle (皮克定理)

Triangle
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 5646   Accepted: 2433

Description

lattice point is an ordered pair (xy) 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 x1y1x2y2x3, and y3, where (x1y1), (x2y2), and (x3y3) are the coordinates of vertices of the triangle. All triangles in the input will be non-degenerate (will have positive area), and −15000 ≤ x1y1x2y2x3y3 ≤ 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

Source


大体题意:

给你三角形的三个顶点(都是int整数),求三角形内部整数点的个数(不包括边界)

思路:

用到了皮克定理:S = a + b / 2 -1;

S为三角形面积,a为内部点的个数,b为边界点的个数。

1.面积用叉积求出

2.边界点:

比如说 一条线段两个端点(x1,y1)和(x2,y2),那么这个线段的整数点个数为gcd(x2-x1,y2-y1);  其中gcd()为最大公约数!

满足等式求解即可!

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<cstdlib>
using namespace std;
const int co = 15000;
int gcd(int a,int b){
	return b == 0 ? a : gcd(b,a%b);
}
int main(){
	int x1,y1,x2,y2,x3,y3;
	while(scanf("%d%d%d%d%d%d",&x1,&y1,&x2,&y2,&x3,&y3) == 6 && (x1 || y1 || x2 || y2 ||x3 || y3)){
		x1+=co;y1+=co;
		x2+=co;y2+=co;
		x3+=co;y3+=co;
		double s = fabs((x2-x1) * (y3-y1) * 1.0 - (y2-y1) * (x3-x1) * 1.0)/2.0;
		int on = gcd(abs(x2-x1),abs(y2-y1)) + gcd(abs(x3-x2),abs(y3-y2)) + gcd(abs(x3-x1),abs(y3-y1));
		double ans = s - on*1.0/2+1;
		printf("%.0f\n",ans);
	}
	return 0;
}


你可能感兴趣的:(C语言)