题目:http://poj.org/problem?id=1269
Description
We all know that a pair of distinct points on a plane defines a line and that a pair of lines on a plane will intersect in one of three ways: 1) no intersection because they are parallel, 2) intersect in a line because they are on top of one another (i.e. they are the same line), 3) intersect in a point. In this problem you will use your algebraic knowledge to create a program that determines how and where two lines intersect.
Output
There should be N+2 lines of output. The first line of output should read INTERSECTING LINES OUTPUT. There will then be one line of output for each pair of planar lines represented by a line of input, describing how the lines intersect: none, line, or point. If the intersection is a point then your program should output the x and y coordinates of the point, correct to two decimal places. The final line of output should read "END OF OUTPUT".
Sample Input
5END OF OUTPUT
这道题说是计算几何,其实用解析几何做就可以了。
给你两条直线,每条直线给两个点(两点确定一条直线嘛~)
判断这两条直线是:相交or相离or重合
嗯,就是给两个点,求直线方程~\(≧▽≦)/~啦啦啦
首先是判断两条直线斜率是否都存在,如果斜率都不存在则平行或重合,判断两条直线的横坐标是否相等,相等则重合,不相等则平行。(垂直于x轴)
再处理只有一个斜率存在,只有一个斜率存在,那肯定就是相交,因为平行和重合的之前判断过了。
交点可以确定了,就是斜率不存在那条直线的横坐标,显然直接通过方程求纵坐标即可。
最后处理两条直线斜率都存在。
那就判断斜率是否相等,再判断斜距是否相等:
斜率相等:
斜距相等→重合
斜距不等→平行
斜率不相等,相交。
知道两条直线的方程,求交点坐标,应该不用说了。
注意一下输出格式问题,OK,AC咯~
#include <stdio.h> struct Point { double x,y; }; struct Line { Point a,b; }; // 为0则平行,为1则同一条直线,为2则相交于一点. int ispos; // 交点坐标及斜率、斜距值 double p_x,p_y,k1,k2,b1,b2; double abs(double x) { return x<0?-x:x; } bool find_k(Line l,int num) { if(l.a.x==l.b.x) return false; if(num==1) { k1=(l.b.y-l.a.y)/(l.b.x-l.a.x); b1=l.a.y-k1*l.a.x; } else { k2=(l.b.y-l.a.y)/(l.b.x-l.a.x); b2=l.a.y-k2*l.a.x; } return true; } void judge(Line m,Line n) { // 两条直线斜率K都不存在,即两直线都垂直于x轴 // 这里用 & ,让两个函数务必都执行,这样k1,k2,b1,b2都算出来了,可以直接调用了 if(!find_k(m,1) & !find_k(n,2)) { if(m.a.x==n.a.x) ispos=1; return; } // 有任何一条直线斜率K不存在 if(!find_k(m,1)) { p_x=m.a.x; p_y=k2*p_x+b2; ispos=2; return; } else if(!find_k(n,2)) { p_x=n.a.x; p_y=k1*p_x+b1; ispos=2; return; } // 两条直线斜率k都存在 if(k1==k2) { if(b1==b2) ispos=1; return; } p_x=(b2-b1)/(k1-k2); p_y=k1*p_x+b1; ispos=2; return; } int main() { int n; Line l1,l2; scanf("%d",&n); printf("INTERSECTING LINES OUTPUT\n"); while(n--) { p_x=p_y=k1=k2=b1=b2=0; scanf("%lf%lf%lf%lf%lf%lf%lf%lf",&l1.a.x,&l1.a.y,&l1.b.x,&l1.b.y,&l2.a.x,&l2.a.y,&l2.b.x,&l2.b.y); ispos=0; judge(l1,l2); if(!ispos) printf("NONE\n"); else if(ispos==1) printf("LINE\n"); else printf("POINT %.2lf %.2lf\n",p_x,p_y); } printf("END OF OUTPUT\n"); return 0; }