题目链接:https://vjudge.net/problem/POJ-1269
题意:给出4个顶点,表示两条直线,求这两条直线的相交情况,重合输出LINE,平行输出NONE,相交于一点输出该点的距离。
思路:
用叉积判断直线的重合和平行,并且可以用叉积求相交直线的交点。
用叉积求直线交点的模板:
double t=((a-c)^(c-d))/((a-b)^(c-d)); ans=Point(a.x+(b.x-a.x)*t,a.y+(b.y-a.y)*t)
证明见https://www.cnblogs.com/jklover/p/10484313.html。
AC code:
#include<cstdio> #include<algorithm> #include<cmath> #include<cstdlib> using namespace std; const double eps=1e-8; int T,flag; double x1,yy1,x2,yy2,x3,yy3,x4,yy4; struct Point{ double x,y; Point(){} Point(double xx,double yy):x(xx),y(yy){} Point operator + (const Point& b)const{ return Point(x+b.x,y+b.y); } Point operator - (const Point& b)const{ return Point(x-b.x,y-b.y); } double operator * (const Point& b)const{ return x*b.x+y*b.y; } double operator ^ (const Point& b)const{ return x*b.y-b.x*y; } }ans; struct Line{ Point s,e; Line(){}; Line(Point ss,Point ee){ s=ss,e=ee; } }; int sgn(double x) { if(abs(x) < eps)return 0; if(x < 0)return -1; else return 1; } void solve(){ Point a=Point(x1,yy1); Point b=Point(x2,yy2); Point c=Point(x3,yy3); Point d=Point(x4,yy4); if(sgn((b-a)^(d-c))==0){ if(sgn((c-a)^(d-a))==0) flag=0; else flag=1; return; } flag=2; double t=((a-c)^(c-d))/((a-b)^(c-d)); ans=Point(a.x+(b.x-a.x)*t,a.y+(b.y-a.y)*t); } int main(){ scanf("%d",&T); printf("INTERSECTING LINES OUTPUT "); while(T--){ scanf("%lf%lf%lf%lf%lf%lf%lf%lf",&x1,&yy1,&x2,&yy2,&x3,&yy3,&x4,&yy4); solve(); if(flag==0) printf("LINE "); else if(flag==1) printf("NONE "); else printf("POINT %.2f %.2f ",ans.x,ans.y); } printf("END OF OUTPUT "); return 0; }