判断线段相交

来源:互联网 发布:demo设计软件 编辑:程序博客网 时间:2024/05/16 04:02
  1. #include<cstdio>  
  2. #include<cstring>  
  3. #include<cmath>  
  4. #include<cstdlib>  
  5. #include<iostream>  
  6. #include<algorithm>  
  7. #include<sstream>  
  8. #include<fstream>  
  9. #include<vector>  
  10. #include<map>  
  11. #include<stack>  
  12. #include<list>  
  13. #include<set>  
  14. #include<queue>  
  15. #define LL long long  
  16. #define lson l,m,rt<<1  
  17. #define rson m+1,r,rt<<1 | 1  
  18. using namespace std;  
  19. const int maxn=100005,inf=1<<29;  
  20. int dir[][2]={ {0,1},{-1,0},{0,-1},{1,0},{-1,1},{-1,-1},{1,-1},{1,1}};  
  21. int n,m,t;  
  22. double EPS=1e-10;  
  23. double add(double a,double b)  
  24. {  
  25.     if(abs(a+b)<EPS*(abs(a)+abs(b))) return 0;  
  26.     return a+b;  
  27. }  
  28. struct P  
  29. {  
  30.     double x,y;  
  31.     P(){}  
  32.     P(double x,double y):x(x),y(y){}  
  33.     P operator +(P p)  
  34.     {  
  35.         return P(add(x,p.x),add(y,p.y));  
  36.     }  
  37.     P operator -(P p)  
  38.     {  
  39.         return P(add(x,-p.x),add(y,-p.y));  
  40.     }  
  41.     P operator *(double d)  
  42.     {  
  43.         return P(x*d,y*d);  
  44.     }  
  45.     double dot(P p)//内积  
  46.     {  
  47.         return add(x*p.x,y*p.y);  
  48.     }  
  49.     double det(P p)//外积  
  50.     {  
  51.         return add(x*p.y,-p.x*y);  
  52.     }  
  53. };  
  54. struct v  
  55. {  
  56.     P p,q;  
  57. }a[maxn];  
  58. bool on_seg(P p1,P p2,P q)//判断点q是否在线段p1p2上  
  59. {  
  60.     return (p1-q).det(p2-q)==0&&(p1-q).dot(p2-q)<=0;  
  61. }  
  62. P intersection(P p1,P p2,P q1,P q2)//计算两线段的交点  
  63. {  
  64.     return p1+(p2-p1)*((q2-q1).det(q1-p1)/(q2-q1).det(p2-p1));  
  65. }  
  66. bool judge(v s1,v s2)  
  67. {  
  68.     if((s1.p-s1.q).det(s2.p-s2.q)==0)  
  69.     {  
  70.         return on_seg(s1.p,s1.q,s2.p)||  
  71.                     on_seg(s1.p,s1.q,s2.q)||  
  72.                     on_seg(s2.p,s2.q,s1.p)||  
  73.                     on_seg(s2.p,s2.q,s1.q);  
  74.     }  
  75.     else  
  76.     {  
  77.         P r=intersection(s1.p,s1.q,s2.p,s2.q);  
  78.         //cout<<"x = "<<r.x<<" y= "<<r.y<<endl;  
  79.         return on_seg(s1.p,s1.q,r)&&on_seg(s2.p,s2.q,r);  
  80.     }  
  81. }  
  82. int main()  
  83. {  
  84.   
  85.     while(cin>>n,n)  
  86.     {  
  87.         for(int i=0;i<n;i++) cin>>a[i].p.x>>a[i].p.y>>a[i].q.x>>a[i].q.y;  
  88.         //cin>>s2.p.x>>s2.p.y>>s2.q.x>>s2.q.y;  
  89.         int cnt=0;  
  90.         for(int i=0;i<n;i++)  
  91.             for(int j=i+1;j<n;j++)  
  92.             if(judge(a[i],a[j])) cnt++;  
  93.         cout<<cnt<<endl;  
  94.     }  
  95.     return 0;  
  96. }
  97. 转载自:http://blog.csdn.net/u013615904/article/details/46917431