Shirlies
宁静专注认真的程序媛~

判断线段相交问题,其实还以为会超时的,结果良好^_^

代码如下:
 1 #include <cstdio>
 2 #include <cmath>
 3 #include <algorithm>
 4 
 5 struct point
 6 {
 7     double x,y;
 8 };
 9 
10 struct node
11 {
12     point aa,bb;
13 }segment[100100];
14 
15 int n;
16 int stack[100100];
17 
18 double cross_product(point &a,point &b,point &o)
19 {
20     return (a.x - o.x) * (b.y - o.y) - (b.x - o.x) * (a.y - o.y);
21 }
22 
23 bool on_segment(node &a,point &b)
24 {
25     int minx = std::min(a.aa.x,a.bb.x);
26     int miny = std::min(a.aa.y,a.bb.y);
27     int maxx = std::min(a.aa.x,a.bb.x);
28     int maxy = std::min(a.aa.y,a.bb.y);
29     if(b.x> minx&&b.x < maxx&&b.y < maxy&&b.y > miny)
30         return true;
31 
32     return false;
33 }
34 
35 bool segment_cross(node &a,node &b)
36 {
37     double s1 = cross_product(a.aa,a.bb,b.aa);
38     double t1 = cross_product(a.aa,a.bb,b.bb);
39     double s2 = cross_product(b.aa,b.bb,a.aa);
40     double t2 = cross_product(b.aa,b.bb,a.bb);
41     if(s1 * t1 < 0&&s2 * t2 < 0)
42         return true;
43     else if(s1 == 0 && on_segment(a,b.aa))
44         return true;
45     else if(t1 == 0 && on_segment(a,b.bb))
46         return true;
47     else if(s2 == 0 && on_segment(b,a.aa))
48         return true;
49     else if(t2 == 0 && on_segment(b,a.bb))
50         return true;
51 
52     return false;
53 }
54 
55 int main()
56 {
57     while(scanf("%d",&n),n)
58     {
59         for(int i = 0;i < n;i ++)
60         {
61             scanf("%lf%lf%lf%lf",&segment[i].aa.x,&segment[i].aa.y,&segment[i].bb.x,&segment[i].bb.y);
62         }
63         int top = 0;
64         for(int i = n-2;i >= 0;i --)
65         {
66             int flag = 1;
67             for(int j = i + 1;j < n;j ++)
68             {
69                 if(segment_cross(segment[i],segment[j]))
70                 {
71                     flag = 0;
72                     break;
73                 }
74             }
75             if(flag)
76             {
77                 stack[top ++] = i;
78             }
79         }
80 
81         printf("Top sticks: ");
82         for(int i = top - 1;i >= 0;i --)
83         {
84             printf("%d, ",stack[i]+1);
85         }
86         printf("%d.\n",n);
87     }
88 
89     return 0;
90 }

 

 

posted on 2012-05-21 15:10  Shirlies  阅读(228)  评论(0编辑  收藏  举报