题目大致意思:给若干点形成多边形,再给出一些点判断是在多边形内还是外.
一道模板题...数学不行,自己写不出来,大致思想是懂的,上网搜了下,有很多种方法,其中一种是作该点平行于x轴的射线,然后判断交点的个数,奇数则在里面,偶数在外面.要注意的是当射线经过多边形的顶点时不计数.哎,数学太弱了,看来要恶补一下了.代码如下:
#include <stdio.h>
#include <math.h>
#define max(a,b) ((a)>(b)?(a):(b))
#define min(a,b) ((a)<(b)?(a):(b))
#define INFINITY 1e9
#define ESP 1e-7
#define MAX_N 100
struct Point
{
double x,y;
};
struct LineSegment
{
Point pt1,pt2;
};
// 计算叉乘 |P1P0| × |P2P0|
double Multiply(Point p1,Point p2,Point p0)
{
return ((p1.x-p0.x)*(p2.y-p0.y)-(p2.x-p0.x)*(p1.y-p0.y));
}
bool IsOnline(Point point,LineSegment line)
{
return( (fabs(Multiply(line.pt1,line.pt2,point))<ESP)&&
((point.x-line.pt1.x)*(point.x-line.pt2.x)<=0)&&
((point.y-line.pt1.y)*(point.y-line.pt2.y)<=0) );
}
// 判断线段相交
bool Intersect(LineSegment L1,LineSegment L2)
{
return( (max(L1.pt1.x,L1.pt2.x)>=min(L2.pt1.x,L2.pt2.x))&&
(max(L2.pt1.x,L2.pt2.x)>=min(L1.pt1.x, L1.pt2.x))&&
(max(L1.pt1.y,L1.pt2.y)>=min(L2.pt1.y,L2.pt2.y))&&
(max(L2.pt1.y,L2.pt2.y)>=min(L1.pt1.y,L1.pt2.y))&& //跨立排斥
(Multiply(L2.pt1,L1.pt2,L1.pt1)*Multiply(L1.pt2,L2.pt2,L1.pt1)>=0)&&
(Multiply(L1.pt1,L2.pt2,L2.pt1)*Multiply(L2.pt2,L1.pt2,L2.pt1)>=0) );
}
// 判断点在多边形内
int InPolygon(Point polygon[],int n,Point point)
{
if(n==1)
return ( (fabs(polygon[0].x-point.x)<ESP)&&(fabs(polygon[0].y-point.y)<ESP) );
else if(n==2)
{
LineSegment side;
side.pt1=polygon[0];
side.pt2=polygon[1];
return IsOnline(point,side);
}
int count=0,i;
LineSegment line;
line.pt1=point;
line.pt2.y=point.y;
line.pt2.x=-INFINITY;
for(i=0;i<n;i++)
{
LineSegment side;
side.pt1=polygon[i];
side.pt2=polygon[(i+1)%n];
if(IsOnline(point,side))
return true;
// 如果side平行x轴则不作考虑
if(fabs(side.pt1.y-side.pt2.y)<ESP)
continue;
//4.一个端点在直线上
if(IsOnline(side.pt1,line))
{
if(side.pt1.y>side.pt2.y)
count++;
}
else if(IsOnline(side.pt2,line))
{
if(side.pt2.y>side.pt1.y)
count++;
}
//相交
else if(Intersect(line,side))
count++;
}
return count%2;
}
int main()
{
// freopen("in.txt","r",stdin);
int n,m,caseNum=0,i;
Point polygon[MAX_N];
Point P;
while(scanf("%d",&n)&&n)
{
caseNum++;
if(caseNum>1)
printf("\n");
printf("Problem %d:\n",caseNum);
scanf("%d",&m);
for(i=0;i<n;i++)
scanf("%lf %lf",&polygon[i].x,&polygon[i].y);
for(i=0;i<m;i++)
{
scanf("%lf %lf",&P.x,&P.y);
if(InPolygon(polygon,n,P))
printf("Within\n");
else
printf("Outside\n");
}
}
return 0;
}