Points Within

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

#include <iostream>
#include <cstdio>
#include <cmath>
#define eps 1e-10
#define N 110
using 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;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值