标签:style blog http color os 使用 io strong ar
转自: http://blog.csdn.net/dgq8211/article/details/7952825
如图,如何求得直线 AB 与直线 CD 的交点P?
以上内容摘自《算法艺术与信息学竞赛》。
思路就是利用叉积求得点P分线段DC的比,然后利用高中学习的定比分点坐标公式求得分点P的坐标。
看不懂的可以去复习下 定比分点 的知识。
1 #include <math.h> 2 #include <stdio.h> 3 #include <string.h> 4 #include <algorithm> 5 using namespace std; 6 7 #define N 105 8 9 const double eps = 1e-6; 10 11 const double Pi = acos(-1.0); 12 13 struct Point 14 { 15 Point(){} 16 Point(double x,double y):x(x),y(y){} 17 double x,y; 18 }; 19 20 struct Seg 21 { 22 Point p1,p2; 23 }; 24 25 int sgn(double x) 26 { 27 return x<-eps ? -1 : (x>eps); 28 } 29 30 double Cross(const Point& p1,const Point& p2,const Point& p3,const Point& p4) 31 { 32 return (p2.x-p1.x)*(p4.y-p3.y) - (p2.y-p1.y)*(p4.x-p3.x); 33 } 34 35 double Area(const Point& p1,const Point& p2,const Point& p3) 36 { 37 return Cross(p1,p2,p1,p3); 38 } 39 40 double fArea(const Point& p1,const Point& p2,const Point& p3) 41 { 42 return fabs(Area(p1,p2,p3)); 43 } 44 45 bool Meet(const Point& p1,const Point& p2,const Point& p3,const Point& p4) 46 { 47 return max(min(p1.x,p2.x),min(p3.x,p4.x)) <= min(max(p1.x,p2.x),max(p3.x,p4.x)) 48 && max(min(p1.y,p2.y),min(p3.y,p4.y)) <= min(max(p1.y,p2.y),max(p3.y,p4.y)) 49 && sgn(Cross(p3,p2,p3,p4) * Cross(p3,p4,p3,p1)) >= 0 50 && sgn(Cross(p1,p4,p1,p2) * Cross(p1,p2,p1,p3)) >= 0; 51 } 52 53 Point Inter(const Point& p1,const Point& p2,const Point& p3,const Point& p4) 54 { 55 double k = fArea(p1,p2,p3) / fArea(p1,p2,p4); 56 return Point((p3.x + k*p4.x)/(1+k),(p3.y + k*p4.y)/(1+k)); 57 }
代码方面,我并没有按照书上的写法来写,而是直接求出“比”k,然后利用通分前的公式计算。
书上那样写可能是因为前面已经求得了两个叉积,直接使用更方便的关系。
下面是书中的写法。
1 Point Inter(const Point& p1,const Point& p2,const Point& p3,const Point& p4) 2 { 3 double s1 = fArea(p1,p2,p3) , s2 = fArea(p1,p2,p4); 4 return Point((p4.x*s1+p3.x*s2)/(s1+s2),(p4.y*s1+p3.y*s2)/(s1+s2)); 5 }
Ps:
1、求交点之前,要保证两条直线不共线。
2、如果是求两条线段的交点,先判断两条线段是否相交。
若相交,则问题可转化成两条直线求交点。
标签:style blog http color os 使用 io strong ar
原文地址:http://www.cnblogs.com/someblue/p/3945624.html