Orchard Trees
An Orchardist has planted an orchard in a rectangle with trees uniformly spaced in both directions. Thus the trees form a rectangular grid and we can consider the trees to have integer coordinates. The origin of the coordinate system is at the bottom left of the following diagram:
Consider that we now overlay a series of triangles on to this grid. The vertices of the triangle can have any real coordinates in the range 0.0 to 100.0, thus trees can have coordinates in the range 1 to 99. Two possible triangles are shown.
Write a program that will determine how many trees are contained within a given triangle. For the purposes of this problem, you may assume that the trees are of point size, and that any tree (point) lying exactly on the border of a triangle is considered to be in the triangle.
Input will consist of a series of lines. Each line will contain 6 real numbers in the range 0.00 to 100.00 representing the coordinates of a triangle. The entire file will be terminated by a line containing 6 zeroes (0 0 0 0 0 0).
Output will consist of one line for each triangle, containing the number of trees for that triangle right justified in a field of width 4.
1.5 1.5 1.5 6.8 6.8 1.5 10.7 6.9 8.5 1.5 14.5 1.5 0 0 0 0 0 0
15 17
这个题最关键的是数学知识,在三角形内和边线上的点与三个顶点连线形成的三个三角形的面积和等于原三角形的面积。知道了这个,对于解决这个题就不难了,但仅限于解决。想A了这道题,一定要好好注意浮点数问题,所以在平常做题的时候浮点数运算能避开就避开(不用海伦公式的原因)。
AC代码:(0.172s)
#include <stdio.h> #include <math.h> #define min(a,b) ((a)<(b)?(a):(b)) #define max(a,b) ((a)>(b)?(a):(b)) typedef struct { double x; double y; }Point; double directArea2(Point p1, Point p2, Point p3) { return fabs(p1.x * p2.y + p1.y * p3.x + p2.x * p3.y - p2.y * p3.x - p1.y * p2.x - p1.x * p3.y); } int main(int argc, const char * argv[]) { Point p1, p2, p3, po; while (scanf("%lf %lf %lf %lf %lf %lf", &p1.x, &p1.y, &p2.x, &p2.y, &p3.x, &p3.y) == 6) { if (p1.x == 0 && p1.y == 0 && p2.x == 0 && p2.y == 0 && p3.x == 0 && p3.y == 0) { break; } int count = 0; double i, j; int minX = max(1, ceil(min(p1.x, min(p2.x, p3.x)))); int maxX = min(99, (int)max(p1.x, max(p2.x, p3.x))); int minY = max(1, ceil(min(p1.y, min(p2.y, p3.y)))); int maxY = min(99, (int)max(p1.y, max(p2.y, p3.y))); double area123 = directArea2(p1, p2, p3); for (i = minX; i <= maxX; i++) { for (j = minY; j <= maxY; j++) { po.x = i; po.y = j; double areaO12 = directArea2(po, p1, p2); double areaO23 = directArea2(po, p2, p3); double areaO13 = directArea2(po, p3, p1); if (fabs(area123 - (areaO12 + areaO13 + areaO23)) < 1e-9) { count++; } } } printf("%4d\n", count); } return 0; }