题目链接:http://poj.org/problem?id=1269
题目大意:给定两条直线,判断两条直线共线、平行、相交。若相交,求出交点。
思路:考察叉积的应用。
#include <iostream>
#include <cmath>
#include <cstdio>
using namespace std;
const int INF = 100010;
struct Point {
int x, y;
};
Point point[4];
int direction(Point p1, Point p2, Point p3) {
//(p3-p1)x(p2-p1)
return (p3.x-p1.x)*(p2.y-p1.y) - (p3.y-p1.y)*(p2.x-p1.x);
}
int main()
{
int t, i;
freopen("/home/lsy/Desktop/2.txt", "r", stdin);
cin >> t;
cout << "INTERSECTING LINES OUTPUT" << endl;
while(t--) {
for(i=0; i<4; i++) cin >> point[i].x >> point[i].y;
//判断是否共线
if(0 == direction(point[2], point[3], point[0]) && 0 == direction(point[2], point[3], point[1])) cout << "LINE" << endl;
//判断是否平行(斜率相等,斜率为0,不存在)
else if((point[0].x-point[1].x)*(point[2].y-point[3].y) == (point[0].y-point[1].y)*(point[2].x-point[3].x))
cout << "NONE" << endl;
/*
这题是直线,所以两条直线一共有3种情况.前两种情况否定了,那么只能是第3种情况了。
假设p0是交点。p1,p0,p2共线,p3,p4,p0共线。(p1-p0)x(p2-p0) = 0; (p3-p0)x(p4-p0) = 0;
将上面的两个方程化为以(x0,y0)为未知数的方程。然后求解即可。因为斜率不相等,所以分母不会为0;
假如写出p1,p2和p3,p4的方程的话,那么斜率有可能不存在。
*/
else {
int a1 = point[0].y - point[1].y;
int b1 = point[1].x - point[0].x;
int c1 = point[0].x*point[1].y - point[1].x*point[0].y;
int a2 = point[2].y - point[3].y;
int b2 = point[3].x - point[2].x;
int c2 = point[2].x*point[3].y - point[3].x*point[2].y;
double x = (c1*b2 - c2*b1)*1.0 / (a2*b1 - a1*b2);
double y = (a2*c1 - a1*c2)*1.0 / (a1*b2 - a2*b1);
printf("POINT %.2lf %.2lf\n",x,y);
}
}
cout << "END OF OUTPUT" << endl;
return 0;
}