1. 程式人生 > >【判斷直線相對位置關係】 POJ 1269

【判斷直線相對位置關係】 POJ 1269

月光林地傳送門

【題目大意】給定n組資料,每一組資料是四個互不相同的點,前兩個點P1,P2表示直線l1,後兩個點Q1,Q2表示直線l2。

給你P1,P2,Q1,Q2的座標,判斷l1和l2的關係【平行、重合、相交】,如果相交要把交點座標算出來。

模板題。用叉積判位置。兩個向量a、b如果叉積為0,則平行或重合——把一個點到另一條直線上兩點的兩個向量叉積一下,若為0則重合,非0就平行。

如果叉積不為0,就套公式求交點。【時空扭曲】

【程式碼】:

#include<iostream>
#include<cstdio>
using namespace std;
struct point{
	double x,y;
	point(double m=0,double n=0){x=m,y=n;}
	friend inline point operator +(const point &a,const point &b){
		return point(a.x+b.x,a.y+b.y);
	}
	friend inline point operator -(const point &a,const point &b){
		return point(a.x-b.x,a.y-b.y);
	}
	friend inline double operator *(const point &a,const point &b){
		return a.x*b.y-a.y*b.x;
	}
	friend inline point operator *(const point &a,const double &k){
		return point(a.x*k,a.y*k);
	}
	friend inline point operator /(const point &a,const double &k){
		return point(a.x/k,a.y/k);
	}
	friend inline double dot(const point &a,const point &b){
		return a.x*b.x+a.y*b.y;
	}
}a,b,c,d;
bool on(const point &x,const point &y,const point &z){
	double det=(x-z)*(y-z);
	if(det!=0)
		return 0;
	return 1;
}
int T;
int main(){
	printf("INTERSECTING LINES OUTPUT\n");
	scanf("%d",&T);
	while(T--){
		cin>>a.x>>a.y;
		cin>>b.x>>b.y;
		cin>>c.x>>c.y;
		cin>>d.x>>d.y;
		double det=(b-a)*(d-c);
		if(det==0){
			if(on(c,d,a)){
				puts("LINE");
				continue;
			}
			puts("NONE");
		}
		else{
			double S1=(c-a)*(c-d);
			double S2=(c-d)*(c-b);
			double k=S1/(S1+S2);
			point E=(b-a)*k;
			printf("POINT %.2lf %.2lf\n",a.x+E.x,a.y+E.y);
		}
	}
	puts("END OF OUTPUT\n");
}