在一个变长为100的矩形果园中均匀载着果树,
果树坐标为(i,j), 1<= i, j <= 99,
其中i,j均为整数。给出三角形的三个点的坐标(浮点数),
问落在三角形内及三角形边上的果树有多少棵?
资料:http://www.cnblogs.com/cgwolver/archive/2008/07/31/1257611.html
#include <cstdio>
#include <cmath>
#include <iostream>
using namespace std;
#define min(a,b) ((a)<(b)?(a):(b))
#define max(a,b) ((a)>(b)?(a):(b))
struct node
{
double x,y;
node(double a,double b):x(a),y(b){}
node(){}
};
typedef node vec;
vec operator - ( node a,node b)
{
return vec(a.x-b.x,a.y-b.y);
}
node a,b,c,d;
double area(node a,node b,node c)
{
vec AB = b-a;
vec AC = c-a;
return fabs(AB.x*AC.y - AB.y*AC.x)/2.0;
}
int main()
{
int i,j,miix,maax,miiy,maay,cnt;
double aa,bb,cc,dd;
while(scanf("%lf%lf%lf%lf%lf%lf",&a.x,&a.y,&b.x,&b.y,&c.x,&c.y))
{
if(a.x==0&&a.y==0&&b.x==0&&b.y==0&&c.x==0&&c.y==0)
break;
miix = max(1,ceil(min(a.x,min(b.x,c.x))));
maax = min(99,int(max(a.x,max(b.x,c.x))));
miiy = max(1,ceil(min(a.y,min(b.y,c.y))));
maay = min(99,int(max(a.y,max(b.y,c.y))));
cnt=0;
/*
方法2:三个部分面积与总面积相等的法
S(PAB) + S(PAC) + S( PBC) = S(ABC) 则判定在三角形之内
*/
dd = area(a,b,c);
for(i=miix;i<=maax;i++)
{
for(j=miiy;j<=maay;j++)
{
d.x = i;
d.y = j;
aa = area(d,a,b);
bb = area(d,a,c);
cc = area(d,b,c);
if(fabs(dd-aa-bb-cc)<1e-8)
cnt++;
}
}
printf("%4d\n",cnt);
}
return 0;
}