UVa 10078 - The Art Gallery

题目:判断多边形是否是凸多边形。

分析:计算几何、凸包。求凸包,判断是否所有点在凸包上,而不是在凸包内即可。

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

using namespace std;

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

//线结构 
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;
 
//叉乘ab*ac 
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);
}

//点到点距离 
double dist( point a, point b )
{
	return (a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y);
}

//坐标排序 
bool cmp1( point a, point b )
{
	return (a.x==b.x)?(a.y<b.y):(a.x<b.x);
}

//级角排序 
bool cmp2( point a, point b )
{
	double cp = crossproduct( P0, a, b );
	if ( cp == 0 ) return a.d < b.d;
	else return cp > 0;
}

//计算凸包 
int Graham( point *P, int n )
{
	if ( n < 3 ) return n;
	sort( P+0, P+n, cmp1 );
	for ( int i = 1 ; i < n ; ++ i )
		P[i].d = dist( P[0], P[i] );
	P0 = P[0];
	sort( P+1, P+n, cmp2 );
	int top = n;
	if ( n > 2 ) {
		top = 1;
		for ( int i = 2 ; i < n ; ++ i ) {
			while ( top > 0 && crossproduct( P[top-1], P[top], P[i] ) <= 0 ) -- top;
			P[++ top] = P[i];
		}
		P[++ top] = P[0];
	}
	return top;
}

//点在直线上 
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 = 0.0+a.dx*(b.y-a.y)-a.dy*(b.x-a.x);
	double t2 = 0.0+a.dx*(b.y+b.dy-a.y)-a.dy*(b.x+b.dx-a.x);
	double t3 = 0.0+b.dx*(a.y-b.y)-b.dy*(a.x-b.x);
	double t4 = 0.0+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] = {-5,-5,-5,1005,1005,-5,1005,1005};
	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 false;
			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);
			S[i] = D[i];
		}
		
		int count = Graham( S, n );
		int flag  = 0;
		for ( int i = 0 ; i < n ; ++ i ) 
			if ( count > 2 && in( D[i], S, count ) ) {
				flag = 1;break;
			}
		
		if ( flag ) printf("Yes\n");
		else printf("No\n");
	}
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值