题目意思:
给出8个数值 = 4个坐标 = 2条直线
问两条直线的关系: 相交(交点), 共线,平行;
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <queue>
using namespace std;
#define INF 0x3f3f3f3f
#define eps 1e-8
const int maxn = 1000+3;
int N;
struct Point
{
double x;
double y;
Point(double a = 0.0, double b = 0.0) { x = a; y = b; }
};
struct Line
{
Point u;
Point v;
} L1,L2;
int Sig(double x)
{
return (x > eps) - (x < -eps);
}
double Mult(const Point &p0, const Point &p1, const Point &p2)
{
return (p1.x-p0.x)*(p2.y-p0.y) - (p2.x-p0.x)*(p1.y-p0.y);
}
double Rake(Line L) //求斜率
{
if(!Sig(L.v.x-L.u.x))
return INF;
return (L.v.y - L.u.y)/(L.v.x - L.u.x);
}
int Intersect(Line L1, Line L2) //line instersect in a point
{
int a = Sig(Mult(L2.u, L1.u, L2.v));
int b = Sig(Mult(L2.u, L1.v, L2.v));
if( a*b<0) //相交
return 1;
else if( a*b == 0 ) //共线
return 0;
else //相离 (包括平行)
return -1;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("in","r",stdin);
#endif
cin>>N;
cout<<"INTERSECTING LINES OUTPUT"<<endl;
double k1,k2,b1,b2,x,y;
while(N--)
{
cin>>L1.u.x>>L1.u.y>>L1.v.x>>L1.v.y>>L2.u.x>>L2.u.y>>L2.v.x>>L2.v.y;
int flag = Intersect(L1, L2);
if(flag == 1)
{
k1 = Rake(L1);
b1 = L1.u.y - k1*L1.u.x;
k2 = Rake(L2);
b2 = L2.u.y - k2*L2.u.x;
x = (b2-b1) / (k1-k2);
y = k1*x + b1;
printf("POINT %.2f %.2f\n",x,y);
}
else if(flag == 0)
cout<<"LINE"<<endl;
else
cout<<"NONE"<<endl;
}
cout<<"END OF OUTPUT"<<endl;
return 0;
}
起初我还判断了,斜率等于无穷的情况,后来发现,除以无穷大 就是0了...所以不需要判断. 判断代码:
// if(!Sig(INF-k1) || !Sig(INF-k2)) //存在其中一条直线垂直x轴
// {
// if(!Sig(INF-k1)) //L1 垂直x轴
// {
// x = L1.u.x;
// y = k2*x + b2;
// }
// else //L2 垂直x轴
// {
// x = L2.u.x;
// y = k1*x + b1;
// }
// }
// else
// {
x = (b2-b1) / (k1-k2);
y = k1*x + b1;
// }