线段和多边形的位置关系模板

#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
using namespace std;
const double eps=1e-8;
 
int sgn(double x){
	if(fabs(x)<eps)
		return 0;
	if(x<0)
		return -1;
	else return 1;
}
 
struct point{
	double x,y;
	point(){}
	point(double sx,double sy):x(sx),y(sy){}
	point operator -(const point &w)const{  //相减 
		return point(x-w.x,y-w.y);
	}
	double operator ^(const point &w)const{ //叉积 
		return x*w.y-y*w.x;
	}
	double operator *(const point &w)const{ //点积 
		return x*w.x+y*w.y;
	}
}p[100];
 
struct line{
	point st,ed;
	line(){}
	line(point sa,point sb):st(sa),ed(sb){}
}seg; 
 
bool isCross(line a,line b){  //是否相交 
	return
	max(a.st.x,a.ed.x)>=min(b.st.x,b.ed.x)&&
	max(b.st.x,b.ed.x)>=min(a.st.x,a.ed.x)&&
	max(a.st.y,a.ed.y)>=min(b.st.y,b.ed.y)&&
	max(b.st.y,b.ed.y)>=min(a.st.y,a.ed.y)&&
	sgn((b.st-a.ed)^(a.st-a.ed))*sgn((b.ed-a.ed)^(a.st-a.ed))<=0&&
	sgn((a.st-b.ed)^(b.st-b.ed))*sgn((a.ed-b.ed)^(b.st-b.ed))<=0;
} 
 
bool isOn(point a,line c){  //是否在多边形边上 
	return 
	sgn((c.st-a)^(c.ed-a))==0 &&
	sgn((a.x-c.st.x)*(a.x-c.ed.x))<=0&&
	sgn((a.y-c.st.y)*(a.y-c.ed.y))<=0;
}
 
int isIn(point a,point p[],int n){ //是否在多边形内 
	for(int i=0;i<n;i++){
		double res=((p[i]-a)^(p[(i+1)%n]-a));
		if(sgn(res)<0) 
			return -1; //在多边形外
		else if(isOn(a,line(p[i],p[(i+1)%n])))
			return 0;  //在线上 
	} 
	return 1;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值