題意:給你兩條直線判斷是平行、重合還是相交,若相交還需輸出交點。對於每條直線只給出直線上兩點。
分析:用向量的叉積判斷平行和重合的情況,交點直接解方程求,斜率不存在特殊考慮。需要注意的是,有可能給的兩條直線中有相同的點,不注意的話,判斷共線的時候可能會出錯。
以下附上代碼:
#include <algorithm>
#include <iostream>
#include <sstream>
#include <fstream>
#include <cstring>
#include <cstdio>
#include <vector>
#include <cctype>
#include <cmath>
#include <stack>
#include <queue>
#include <list>
#include <map>
#include <set>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
struct Point{
double x,y;
Point(){}
Point(double x_, double y_) :
x(x_), y(y_) {}
//Point
Point operator - (const Point &b) const{
Point t(x-b.x,y-b.y);
return t;
}
//Vector
double operator ^ (const Point &b) const{
return x*b.y - y*b.x;
}
};
struct Line{
Point p;
double k;
bool exist; //斜率存不存在
Line(){}
Line(Point p_, double k_) :
p(p_), k(k_) {}
Line(Point a, Point b){
p = a;
if(a.x != b.x){
k = (b.y-a.y)/(b.x-a.x);
exist = 1;
}
else exist = 0;
}
};
int n;
Point p1,p2;
Point p3,p4;
bool onLine(Point a, Point b, Point c)
{
Point v1 = b-a;
Point v2 = c-b;
return (v1^v2) == 0;
}
bool parallel(Point a, Point b, Point c, Point d)
{
Point v1 = b-a;
Point v2 = d-c;
return (v1^v2) == 0;
}
Point intersect(Line a, Line b)
{
Point t;
if(a.exist && b.exist){
t.x = (a.k*a.p.x - b.k*b.p.x + b.p.y - a.p.y) / (a.k - b.k);
t.y = a.k*(t.x-a.p.x) + a.p.y;
}
else{
if(!a.exist){
t.x = a.p.x;
t.y = b.k*(t.x-b.p.x) + b.p.y;
}
else if(!b.exist){
t.x = b.p.x;
t.y = a.k*(t.x-a.p.x) + a.p.y;
}
}
return t;
}
int main()
{
while(scanf("%d",&n) != EOF){
puts("INTERSECTING LINES OUTPUT");
for(int i = 0; i < n; i++){
scanf("%lf%lf",&p1.x,&p1.y);
scanf("%lf%lf",&p2.x,&p2.y);
scanf("%lf%lf",&p3.x,&p3.y);
scanf("%lf%lf",&p4.x,&p4.y);
if(onLine(p1,p2,p3) && onLine(p1,p2,p4)){//!!!可能有點重合
puts("LINE");
}
else{
Line l1(p1,p2);
Line l2(p3,p4);
if(parallel(p1,p2,p3,p4)){
puts("NONE");
}
else{
Point p = intersect(l1,l2);
printf("POINT %.2lf %.2lf\n",p.x,p.y);
}
}
}//end of for
puts("END OF OUTPUT");
}
return 0;
}