HDU 1756 Cupid's Arrow(判定点在多边形内)

时间:2022-12-20 22:30:38

HDU 1756 Cupid's Arrow(判定点在多边形内)

http://acm.hdu.edu.cn/showproblem.php?pid=1756

题意:

       给你一个n个顶点的多边形,然后给你m个点的坐标,问你这m个点每个点是否在多边形内?(在边上也算)

分析:

       对于简单多边形(边不自交)有两种方法可以判断,第一种是看该点与多边形每条边构成的三角形面积和是否等于多边形的总面积.

       第二种是刘汝佳<<训练指南>>P271页介绍的射线法模板.

       下面代码采用的就是第二种方法.

AC代码:

#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
const int maxn=100+5;
const double eps=1e-10;
int dcmp(double x)
{
if(fabs(x)<eps) return 0;
return x<0?-1:1;
}
struct Point
{
double x,y;
Point(){}
Point(double x,double y):x(x),y(y){}
}poly[maxn];
typedef Point Vector;
Vector operator-(Point A,Point B)
{
return Vector(A.x-B.x,A.y-B.y);
}
double Dot(Vector A,Vector B)
{
return A.x*B.x+A.y*B.y;
}
double Cross(Vector A,Vector B)
{
return A.x*B.y-A.y*B.x;
}
bool InSegment(Point P,Point A,Point B)
{
return dcmp(Cross(A-P,B-P))==0 && dcmp(Dot(A-P,B-P))<=0;
}
bool PointInPolygon(Point p,Point* poly,int n)
{
int wn=0;
for(int i=0;i<n;++i)
{
if(InSegment(p,poly[i],poly[(i+1)%n])) return true;
int k=dcmp(Cross(poly[(i+1)%n]-poly[i], p-poly[i]));
int d1=dcmp(poly[i].y-p.y);
int d2=dcmp(poly[(i+1)%n].y-p.y);
if(k>0 && d1<=0 && d2>0) wn++;
if(k<0 && d2<=0 && d1>0) wn--;
}
if(wn!=0) return true;
return false;
}

int main()
{
int n,m;
while(scanf("%d",&n)==1)
{
for(int i=0;i<n;++i)
scanf("%lf%lf",&poly[i].x,&poly[i].y);
scanf("%d",&m);
while(m--)
{
Point p;
scanf("%lf%lf",&p.x,&p.y);
printf("%s\n",PointInPolygon(p,poly,n)?"Yes":"No");
}
}
return 0;
}