UVa 143 - Orchard Trees

題目:統計一個平面中在一個三角內的整點數目(包括在邊上)。

分析:計算幾何。這裡利用叉乘判斷方向,以及在線段上的特判。

            先將頂點排序(找左下角,然後利用叉乘),然後判斷在三條直線右側的點滿足題意;

            如果點在三邊上進行特判;

            這裡有一組比較好的數據:71.67 88.3 45.02 49.09 98.49 0.1

說明:可以利用面積的絕對值判斷,代碼量會少些。

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

const double eps = 1e-8;

typedef struct _point
{
	double x, y;
}point;
point P[7];

double crossproduct(point a, point b, point c)
{
	return (b.x - a.x)*(c.y - a.y) - (c.x - a.x)*(b.y - a.y);
}

int in_segment(point p, point a, point b)
{
	if (fabs(p.x - a.x) < eps && fabs(p.y - a.y) < eps) {
		return 1;
	}
	if (fabs(p.x - b.x) < eps && fabs(p.y - b.y) < eps) {
		return 1;
	}
	if (fabs((p.x - b.x)*(a.y - b.y) - (p.y - b.y)*(a.x - b.x)) > eps) {
		return 0;
	}
	if ((p.x - b.x)*(p.x - a.x) < eps && (p.y - b.y)*(p.y - a.y) < eps) {
		return 1;
	}
	return 0;
}

point new_point(double x, double y)
{
	point p;
	p.x = x;
	p.y = y;
	return p;
}

int main()
{
	while (~scanf("%lf%lf",&P[0].x,&P[0].y)) {
		for (int i = 1; i < 3; ++ i) {
			scanf("%lf%lf",&P[i].x,&P[i].y);
		}
		
		// test finish
		int count = 0;
		for (int i = 0; i < 3; ++ i) {
			if (P[i].x == 0) {
				count ++;
			}
			if (P[i].y == 0) {
				count ++;
			}
		}
		if (count == 6) {
			break;
		}
		
		// find the left bottom point
		P[3] = P[0];
		P[4] = P[1];
		P[5] = P[2];
		for (int i = 1; i < 3; ++ i) {
			if (P[3].x == P[i].x) {
				if (P[3].y > P[i].y) {
					P[3] = P[i];
					P[4] = P[(i+1)%3];
					P[5] = P[(i+2)%3];
				}
			}else if (P[3].x > P[i].x) {
				P[3] = P[i];
				P[4] = P[(i+1)%3];
				P[5] = P[(i+2)%3];
			}
		}
		// clock conuter direction
		if (crossproduct(P[3], P[4], P[5]) < eps) {
			P[6] = P[4];
			P[4] = P[5];
			P[5] = P[6];
		}
		
		int ans = 0;
		for (int x = 1; x < 100; ++ x) {
			for (int y = 1; y < 100; ++ y) {
				if (in_segment(new_point(x, y), P[3], P[4]) || 
					in_segment(new_point(x, y), P[4], P[5]) ||
					in_segment(new_point(x, y), P[5], P[3])) {
					ans ++;
					continue;
				}
				if (crossproduct(P[3], P[4], new_point(x, y)) <= eps) {
					continue;
				}
				if (crossproduct(P[4], P[5], new_point(x, y)) <= eps) {
					continue;
				}
				if (crossproduct(P[5], P[3], new_point(x, y)) <= eps) {
					continue;
				}
				ans ++;
			}
		}
		
		printf("%4d\n",ans);
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值