UVa 634 - Polygon

题目:点与多边形关系判断。

分析:计算几何、点与多边形关系。在多边形外找到几个点与已知点连线,判断交点个数即可。会出现以下情况:穿过边,交点个数+1,穿过顶点交点个数+1(-1也可以,这里只是为了保证交点个数的奇偶性)。尝试多个点都满足交,点为奇数个则在多变形呢。如果已知点在多边形边上,则交点的奇偶性会发生变化,直接判断即可。

#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cmath>

using namespace std;

//点结构 
typedef struct pnode
{
	double x,y;
	pnode( double a, double b ){x = a;y = b;}
	pnode(){}
}point;
point D[1005];

//线结构 
typedef struct lnode
{
	double x,y,dx,dy;
	lnode( point a, point b ){x = a.x;y = a.y;dx = b.x-a.x;dy = b.y-a.y;}
	lnode(){}
}line;

//点在线段上 
bool on( point p, line l )
{
	if ( l.dx*(p.y-l.y)-l.dy*(p.x-l.x) == 0 )
	if ( (p.x-l.x)*(p.x-l.x-l.dx) <= 0 )
	if ( (p.y-l.y)*(p.y-l.y-l.dy) <= 0 )
		return true;
	return false;
}

//线段相交 
bool cross( line a, line b )
{
	double t1 = a.dx*(b.y-a.y)-a.dy*(b.x-a.x);
	double t2 = a.dx*(b.y+b.dy-a.y)-a.dy*(b.x+b.dx-a.x);
	double t3 = b.dx*(a.y-b.y)-b.dy*(a.x-b.x);
	double t4 = b.dx*(a.y+a.dy-b.y)-b.dy*(a.x+a.dx-b.x);
	return (t1*t2 <= 0)&&(t3*t4 <= 0);
}

//点在多边形内
bool in( point p, point* P, int n )
{
	double d[4][2] = {-1e6,-1e6,-1e6,1e6,1e6,-1e6,1e6,1e6};
	for ( int t = 0 ; t < 4 ; ++ t ) {
		line s1 = line( p, point( d[t][0], d[t][1] ) );
		int  count = 0;
		for ( int i = 0 ; i < n ; ++ i ) {
			line s2 = line( P[i], P[i+1] );
			if ( on( p, s2 ) ) return true;
			if ( cross( s1, s2 ) ) count ++;
			if ( on( P[i], s1 ) ) count ++;
		}
		if ( count%2 == 0 ) return false; 
	}
	return true;
}

int main()
{
	int n;
	while ( scanf("%d",&n) && n ) {
		for ( int i = 0 ; i <= n ; ++ i )
			scanf("%lf%lf",&D[i].x,&D[i].y);
		D[n+1] = D[n]; 
		D[n+0] = D[0];
		if ( in( D[n+1], D, n ) )
			printf("T\n");
		else printf("F\n");
	}
	return 0;
}


UVa 634 Polygon
您的回应...

也许你感兴趣

换一批

热门标签

更多