题目链接:POJ 2954 Triangle
还是Pick定理,比上道题简单。
#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
const double eps = 1e-10;
struct Point
{
int x, y;
Point(int x=0, int y=0):x(x),y(y) { }
};
typedef Point Vector;
Vector operator + (const Vector& A, const Vector& B)
{
return Vector(A.x+B.x, A.y+B.y);
}
Vector operator - (const Point& A, const Point& B)
{
return Vector(A.x-B.x, A.y-B.y);
}
Vector operator * (const Vector& A, double p)
{
return Vector(A.x*p, A.y*p);
}
bool operator < (const Point& a, const Point& b)
{
return a.x < b.x || (a.x == b.x && a.y < b.y);
}
int dcmp(double x)
{
if(fabs(x) < eps)
return 0;
else
return x < 0 ? -1 : 1;
}
bool operator == (const Point& a, const Point &b)
{
return dcmp(a.x-b.x) == 0 && dcmp(a.y-b.y) == 0;
}
int Cross(const Vector& A, const Vector& B)
{
return A.x*B.y - A.y*B.x;
}
int Area2(Point A, Point B, Point C)
{
return Cross(B - A, C - A);
}
int gcd(int a ,int b)
{
return b == 0 ? a : gcd(b , a % b);
}
Point p[4];
int get_area(int a, int b, int c)
{
return abs(p[a].x * p[b].y + p[c].x * p[a].y + p[b].x * p[c].y - p[c].x * p[b].y - p[a].x * p[c].y - p[b].x * p[a].y);
}
int main()
{
while(scanf("%d%d%d%d%d%d", &p[0].x, &p[0].y, &p[1].x, &p[1].y, &p[2].x, &p[2].y))
{
if(p[0].x ==0 && p[0].y == 0 && p[1].x ==0 && p[1].y == 0 && p[2].x ==0 && p[2].y == 0)
break;
int area = get_area(0, 1, 2);
int dx, dy, edge_point = 0;
p[3] = p[0];
for(int i = 0; i < 3; i++)
{
dx = abs(p[i].x - p[i + 1].x);
dy = abs(p[i].y - p[i + 1].y);
if(dx == 0 && dy == 0)
continue;
if(dx == 0)
edge_point += dy - 1;
else if(dy == 0)
edge_point += dx - 1;
else
edge_point += gcd(dx, dy) - 1;
}
edge_point += 3;
printf("%d\n", (area + 2 - edge_point) / 2);
}
return 0;
}
本文提供了一种使用Pick定理解决POJ2954 Triangle问题的代码实现。通过计算边界上的点数和三角形内部的整点数来确定格点三角形的面积。

被折叠的 条评论
为什么被折叠?



