POJ 1269(计算几何初步——简单处理解析几何,求直线交点)

此题给出N组直线,每组2条直线,求出直线是否相交。

如果共线则输出LINE,相交则输入点坐标,否则输出NONE.

解析几何初中都学过一些,不过写成程序还真是麻烦。

情况分成3种:

1.看直线的横坐标是否相等。

2.看直线的纵坐标是否相等。

3.直接用直线公式求解。

View Code
  1 #include<iostream>
2 #define EPS 1e-8
3 using namespace std;
4
5 bool equal(double x, double y)
6 {
7 return x - y <= EPS && -EPS <= x - y;
8 }
9
10 void X_Get_point(double x1, double x2, double y1, double y2, double x0)
11 {
12 double k = (y2 - y1)/(x2 - x1);
13 double b = y2 - k*x2;
14 double y0 = k*x0 + b;
15 printf("POINT %.2lf %.2lf\n",x0,y0);
16 }//已知X,求Y
17
18 void Y_Get_point(double x1, double x2, double y1, double y2, double y0)
19 {
20 double k = (y2 - y1)/(x2 - x1);
21 double b = y2 - k*x2;
22 double x0 = (y0 - b)/k;
23 printf("POINT %.2lf %.2lf\n",x0,y0);
24 }//已知y,求X
25
26 double cross(double x0, double y0, double x1, double y1)
27 {
28 return y1*x0 - x1*y0;
29 }
30
31 bool on_line(double x1, double x2, double y1, double y2, double x0, double y0)
32 {
33 if (equal(cross(x2-x1,y2-y1,x0-x1,y0-y1),0))return true;
34 return false;
35 }//判断点是否在直线上
36
37 int main()
38 {
39 int T;
40 while (scanf("%d",&T) != EOF) {
41 for (int i(0); i<T; ++i) {
42 if (i == 0)cout<<"INTERSECTING LINES OUTPUT\n";
43 double x[4];
44 double y[4];
45 scanf("%lf%lf%lf%lf%lf%lf%lf%lf",&x[0],&y[0],&x[1],&y[1],&x[2],&y[2],&x[3],&y[3]);
46 if (equal(x[0],x[1])) {
47 if (equal(x[2],x[3])) {
48 if (equal(x[2],x[0])) {
49 cout<<"LINE\n";
50 continue;
51 } else {
52 cout<<"NONE\n";
53 continue;
54 }
55 } else {
56 X_Get_point(x[2],x[3],y[2],y[3],x[0]);
57 continue;
58 }
59 } else {
60 if (equal(x[3],x[2])) {
61 X_Get_point(x[0],x[1],y[0],y[1],x[2]);
62 continue;
63 }
64 }
65
66 if (equal(y[0],y[1])) {
67 if (equal(y[2],y[3])) {
68 if (equal(y[2],y[0])) {
69 cout<<"LINE\n";
70 continue;
71 } else {
72 cout<<"NONE\n";
73 continue;
74 }
75 } else {
76 Y_Get_point(x[2],x[3],y[2],y[3],y[0]);
77 continue;
78 }
79 } else {
80 if (equal(y[2],y[3])) {
81 Y_Get_point(x[0],x[1],y[0],y[1],y[2]);
82 continue;
83 }
84 }
85
86 double k1 = (y[1] - y[0])/(x[1] - x[0]);
87 double k2 = (y[3] - y[2])/(x[3] - x[2]);
88 if (equal(k1,k2)) {
89 if (on_line(x[0],x[1],y[0],y[1],x[2],y[2])) {
90 cout<<"LINE\n";
91 continue;
92 } else {
93 cout<<"NONE\n";
94 }
95 } else {
96 double b1 = y[1] - k1*x[1];
97 double b2 = y[2] - k2*x[2];
98 double y0 = (b2*k1 - b1*k2)/(k1 - k2);
99 double x0 = (y0 - b2)/k2;
100 printf("POINT %.2lf %.2lf\n",x0,y0);
101 continue;
102 }
103 }
104 cout<<"END OF OUTPUT\n";
105 }
106 return 0;
107 }



posted on 2012-01-11 17:44  Dev-T  阅读(842)  评论(0编辑  收藏  举报