Problem Intersecting Lines (POJ 1269)
题目大意
给定两条直线,问两条直线是否重合,是否平行,或求出交点。
解题分析
主要用叉积做,可以避免斜率被0除的情况。
求交点P0: 已知P1 P2 P3 P4
运用 P0P1 X P0P2 = 0 和 P0P3 X P0P4 = 0
C++ 用%.2lf g++ 用 %.2f!!!
C++ 用%.2lf g++ 用 %.2f!!!
C++ 用%.2lf g++ 用 %.2f!!!
参考程序
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
using namespace std; #define eps 1e-8 struct P{
double x,y; P(){}
P(double x,double y):x(x),y(y){} friend P operator +(P a,P b){
return P(a.x+b.x,a.y+b.y);
}
friend P operator -(P a,P b){
return P(a.x-b.x,a.y-b.y);
}
friend double operator *(P a,P b){
return a.x * b.y - a.y * b.x ;
}
friend double operator /(P a,P b){
return a.x * b.x + a.y * b.y ;
}
friend bool operator ==(P a,P b){
return fabs(a.x-b.x)<eps && fabs(a.y-b.y)<eps;
}
friend bool operator !=(P a,P b){
return !(a==b);
}
friend bool operator <(P a,P b){
if (fabs(a.y-b.y)<eps) return a.x<b.x;
return a.y<b.y;
}
friend double turn(P a,P b,P c){ //向量AB X 向量AC
return (b-a)*(c-a);
}
friend void print(P a){
printf("%.2lf %.2lf\n",a.x,a.y);
}
}; struct L{
P a,b;
L(){}
L(P a,P b):a(a),b(b){}
friend P subl(L a){ //向量l
return P(a.b.x-a.a.x,a.b.y-a.a.y);
}
}; bool online(L l,P p){
if (fabs(turn(l.a,l.b,p))<eps) return ;
return ;
}
P solve(double a1,double b1,double c1,double a2,double b2,double c2){
P a;
a.x = (b1*c2-b2*c1)/(a1*b2-a2*b1);
a.y = (a1*c2-a2*c1)/(a2*b1-a1*b2);
return a;
}
void check(L lx,L ly){
if (online(lx,ly.a) && online(lx,ly.b)) printf("LINE\n"); else
if (fabs(subl(lx)*subl(ly))<eps) printf("NONE\n"); else
{
double x1=lx.a.x , y1=lx.a.y;
double x2=lx.b.x , y2=lx.b.y;
double x3=ly.a.x , y3=ly.a.y;
double x4=ly.b.x , y4=ly.b.y;
double a1 = y1 - y2 , b1 = x2 - x1 , c1 = x1*y2 - x2*y1 ;
double a2 = y3 - y4 , b2 = x4 - x3 , c2 = x3*y4 - x4*y3 ;
printf("POINT ");
print(solve(a1,b1,c1,a2,b2,c2));
}
} int main(){
int T;
scanf("%d",&T);
printf("INTERSECTING LINES OUTPUT\n");
while (T--){
double x1,y1,x2,y2,x3,y3,x4,y4;
scanf("%lf%lf%lf%lf%lf%lf%lf%lf",&x1,&y1,&x2,&y2,&x3,&y3,&x4,&y4);
P a(x1,y1),b(x2,y2),c(x3,y3),d(x4,y4);
L lx(a,b),ly(c,d);
check(lx,ly);
}
printf("END OF OUTPUT\n");
}