POJ1410:线段相交

POJ1410

题解:细节很多,需要注意

  • 给出的矩阵左上角和右下角没有必然关系。
  • 线段在矩阵内部也算相交。
  • 规范相交和非规范相交都要考虑。

代码

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <vector>
using namespace std;
double const eps = 1e-8;
int const inf = 0x7f7f7f7f;
int n;
typedef struct Point{   //点和向量
	double x,y;
	Point(){};
	Point(double x,double y):x(x),y(y){};
	Point operator - (const Point& e)const{   //减
		return Point(x - e.x,y - e.y);
	}
	double operator ^ (const Point& e)const{  //叉乘
		return x * e.y - y * e.x;
	}
	double operator * (const Point& e)const{  //点积
		return x * e.x + y * e.y;
	}
}Vector;
Point p1,p2;
struct Line{    //直线的定义
	Point a,b;
	Line(){};
	Line(Point a,Point b):a(a),b(b){}
}line;
int dcmp(double x){    //判断符号
	if(fabs(x) < eps)	return 0;
	else return x < 0 ? -1 : 1;
}
bool onsegment(Point p,Point a1,Point a2){
	return dcmp((a1 - p) ^ (a2 - p)) == 0 && dcmp((a1 - p) * (a2 - p)) <= 0;
}
bool segment_intersection(Line line1,Line line2){  //判断线段是否相交,相交返回true
	double c1 = (line1.b - line1.a) ^ (line2.a - line1.a);
	double c2 = (line1.b - line1.a) ^ (line2.b - line1.a);
	double c3 = (line2.b - line2.a) ^ (line1.a - line2.a);
	double c4 = (line2.b - line2.a) ^ (line1.b - line2.a);
	if(dcmp(c1) * dcmp(c2) < 0 && dcmp(c3) * dcmp(c4) < 0)	return true;
	if(onsegment(line1.a,line2.a,line2.b) || onsegment(line1.b,line2.a,line2.b))	return true;
	if(onsegment(line2.a,line1.a,line1.b) || onsegment(line2.b,line1.a,line1.b))	return true;
}
bool inner(double x,double y){
	if(p1.x < x && x < p2.x && p2.y < y && y < p1.y)	return true;
	else 	return false;
}
bool solve(){
	if(inner(line.a.x,line.a.y) && inner(line.b.x,line.b.y))	return true;
	if(segment_intersection(Line(Point(p1.x,p2.y),Point(p1.x,p1.y)),line))	return true;
	if(segment_intersection(Line(Point(p1.x,p2.y),Point(p2.x,p2.y)),line))	return true;
	if(segment_intersection(Line(Point(p2.x,p1.y),Point(p1.x,p1.y)),line))	return true;
	if(segment_intersection(Line(Point(p2.x,p2.y),Point(p2.x,p1.y)),line))	return true;
	return false;
}
int main(){
	while(~scanf("%d",&n)){
		for(int i=0;i<n;i++){
			scanf("%lf%lf%lf%lf",&line.a.x,&line.a.y,&line.b.x,&line.b.y);  //线段
			scanf("%lf%lf%lf%lf",&p1.x,&p1.y,&p2.x,&p2.y);    
			if(p2.x < p1.x)		swap(p1.x,p2.x);   //矩阵的点
			if(p2.y > p1.y)		swap(p1.y,p2.y);
			if(solve())	printf("T\n");
			else 	printf("F\n");
		}
	}
	return 0;
}

 

猜你喜欢

转载自blog.csdn.net/weixin_42264485/article/details/88924746