您的位置:首页 > 其它

UVa 143 - Orchard Trees

2017-05-16 16:15 274 查看
題目:統計一個平面中在一個三角內的整點數目(包括在邊上)。

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

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

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

            這裡有一組比較好的數據: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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: