Points Within

来源:互联网 发布:音乐系统cms 编辑:程序博客网 时间:2024/06/05 01:43

判断点是否在任意多边形内。

#include <iostream>#include <cstdio>#include <cmath>#define eps 1e-10#define N 110using namespace std;struct Point{      double x, y;      Point(){}      Point(double x, double y):x(x),y(y){}};Point operator - (Point a, Point b){      return Point(a.x-b.x, a.y-b.y);}double operator * (Point a, Point b){      return a.x*b.y-a.y*b.x;}double dcmp(double x){    return fabs(x)<eps?0:x;}//返回点p是否在线段a-b上bool InSegment(Point p,Point a,Point b){    return dcmp((p-a)*(b-a))==0&&dcmp(p.x-min(a.x,b.x))>=0&&            dcmp(p.x-max(a.x,b.x))<=0&&dcmp(p.y-min(a.y,b.y))>=0&&            dcmp(p.y-max(a.y,b.y))<=0;}//返回p是否在多边形p0的内部或边上bool InPolygon(Point p0, Point p[],int n){    int num=0;    Point pp=Point(-1,0);//射线    for(int i=0;i<n;i++)    {        Point a=p[i],b=p[(i+1)%n];        if(InSegment(p0,a,b))//点在线段上            return true;        if(dcmp(a.y-b.y)==0)//            continue;        if(dcmp(a.y-b.y)>0)//            swap(a,b);        if(dcmp((b-p0)*pp)>=0 && dcmp(pp*(a-p0))>0 && dcmp((p0-a)*(b-a)>=0))           num++;    }    return num%2;}int main(){      int n, m, cnt  = 1;      Point p[110], t;      while (~scanf("%d", &n) && n)      {            scanf("%d", &m);            for (int i=0; i<n; i++)                  scanf("%lf%lf", &p[i].x, &p[i].y);            if(cnt>1)                  printf("\n");            printf("Problem %d:\n",cnt++);            while (m--)            {                  scanf("%lf%lf", &t.x, &t.y);                  if (InPolygon(t, p, n))                        printf("Within\n");                  else                        printf("Outside\n");            }      }      return 0;}


原创粉丝点击