以下内容来自 DeepSeek。为了做杀蚂蚁,我特地研究了以下这个东西,做杀蚂蚁做了一天。ljx 大佬 @ljx20130810 只用 4 个小时就做出来了,膜拜 orz。
已知线段 AB 和一点 P,求点 P 到线段 AB 的距离。
可以把点 A,B 也看做从原点出发的向量。那么 AB=(B−A),线段上的任意点 Q=t⋅AB+A,其中 t∈[0,1]。如果 t<0 则表示点 Q 射线 BA 上,如果 t>0 则表示点 Q 在射线 AB 上。
PQ 最短即 ∥PQ∥2 最小,
PQ2=P−A−t⋅AB2=AP2−2t⋅AP⋅AB+t2⋅AB2
可以把 PQ2 看作 t 的函数,这是一个二次函数,可以对其求导,求导结果为:
t⋅AB2−2⋅AP⋅AB
当导数为 0 时,PQ2 得到最小值。
t⋅AB2−2⋅AP⋅AB=0t⋅AB2=2⋅AP⋅ABt=AB22⋅AP⋅AB
我们就知道 t 是多少了。此时我们要对 t 的值分讨。
当 t<0 或者 t>1 时,Q 点不在线段 AB 上,在 AP,BP 的长度中取一个最小值即可。
当 0≤t≤1 时,将 t 带回 Q=t⋅AB+A 可以得到 Q。算出 PQ 即可。
代码实现如下:
C++#define eps 1e-8
namespace Point{// 定义点和向量运算
struct point{double x,y;point(const double &x_ = 0,const double &y_ = 0){x = x_,y = y_;}};
inline point operator+(const point &n1,const point &n2){return point(n1.x+n2.x,n1.y+n2.y);}
inline point operator-(const point &n1,const point &n2){return point(n1.x-n2.x,n1.y-n2.y);}
inline double len(const point &n1){return sqrt(n1.x*n1.x+n1.y*n1.y);}
inline double operator*(const point &n1,const point &n2){return n1.x*n2.x+n1.y*n2.y;}
inline double dst(point p,point a,point b){// 点 p 到线段 ab 的距离
point ap = p-a,ab = b-a,bp = p-b;
double t = ap*ab/(ab.x*ab.x+ab.y*ab.y);
if(t < -eps)return len(ap);
if(t - 1 > eps)return len(bp);
point q = a + point(ab.x*t,ab.y*t);
return len(p-q);
}
}using namespace Point;