给定点 \(Q,P_1,P_2\),问点 \(Q\) 是否在线段 \(P_1P_2\) 上。
首先运用矢量的叉积可以很方便地判断点是否在给定线段的直线上:若 \(Q\) 在直线 \(P_1P_2\) 上,则 \(\overrightarrow{P_1Q}\times \overrightarrow{P_1P_2}=0\)。
然后我们只需要保证点 \(Q\) 在以 \(P_1P_2\) 为对角线的矩形里就可以了。
代码:
#include
#include
#include
#include
#include
using namespace std;
const double eps=1e-10;
struct Point
{
double x,y;
Point (double X,double Y) : x(X),y(Y) {}
Point () {}
void read() { scanf("%lf %lf",&x,&y); }
Point operator - (const Point a) const { return Point(x-a.x,y-a.y); }
double operator * (const Point a) const { return x*a.y-y*a.x; }
}Q,P1,P2;
int main()
{
Q.read(),P1.read(),P2.read();
double MinX=min(P1.x,P2.x),MaxX=max(P1.x,P2.x),MinY=min(P1.y,P2.y),MaxY=max(P1.y,P2.y);
if(fabs((Q-P1)*(P2-P1))=MinX&&Q.x<=MaxX+eps&&Q.y+eps>=MinY&&Q.y<=MaxY+eps)
puts("YES");
else
puts("NO");
return 0;
}
标签:P2,判断,const,Point,是否,线段,P1,double,include
来源: https://www.cnblogs.com/With-penguin/p/13198589.html