POJ 1410 Intersection (判断直线相交模板)

题目链接:POJ 1410

必须注意几点

1、文中给出的左上顶点和右下顶点不保证x1<x2,y1>y2;即需要自己判断

2、线段完全在矩形内部要返回T.

除此之外,判断线段相交时不要忘记考虑线段共线的情况。


#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <stack> 
#include <cstring>
#define eps 1e-8
using namespace std; 
struct Point {
	int x, y;
	Point(int x=0, int y=0):x(x),y(y) {}
};
struct Line {
	Point s, e;
};
typedef Point Vector;
int Cross(Vector p1, Vector p2) {
	return p1.x * p2.y - p2.x * p1.y;
}
Vector operator + (Vector a, Vector b) {
	return Vector(a.x + b.x, a.y + b.y);
}
Vector operator - (Vector a, Vector b) {
	return Vector(a.x - b.x, a.y - b.y);
}
bool Intersection(Point a, Point b, Point c, Point d) {
	Vector ab = b - a, cd = d - c;
	Vector ac = c - a, ad = d - a, ca = a - c, cb = b - c;
	if(Cross(ab, cd) == 0) {   //共线
		if(min(a.x,b.x)<=max(c.x,d.x)&&min(c.x,d.x)<=max(a.x,b.x)&&min(a.y,b.y)<=max(c.y,d.y)&&min(c.y,d.y)<=max(a.y,b.y))
            return 1;   //重叠或首尾相接
        if(min(a.x,b.x)>max(c.x,d.x)||min(c.x,d.x)>max(a.x,b.x)||min(a.y,b.y)>max(c.y,d.y)||min(c.y,d.y)>max(a.y,b.y))
            return 0;  //分离
 }
	if(Cross(ab, ac) * Cross(ab, ad) <= 0 && Cross(cd, ca) * Cross(cd, cb) <= 0) {
		return 1;
	}
	else return 0;
}
int main() {
	int n;
	Line line;
	Point a, b, c, d;
	while(~scanf("%d", &n)) {
		while(n--) {
			scanf("%d %d %d %d %d %d %d %d", &line.s.x, &line.s.y, &line.e.x, &line.e.y, &a.x, &a.y, &c.x, &c.y);
			if(a.x > c.x && a.y > c.y) {    //判断a,c点位置
				int t = a.x;
				a.x = c.x;
				c.x = t;
			}
			else if(a.x < c.x && a.y < c.y) {
				int t = a.y;
				a.y = c.y;
				c.y = t;
			}
			else if(a.x > c.x && a.y < c.y) {
				int t = a.x;
				a.x = c.x;
				c.x = t;
				t = a.y;
				a.y = c.y;
				c.y = t;
			}
			b.x = a.x;
			b.y = c.y;
			d.x = c.x;
			d.y = a.y;
			if(	line.e.x >= a.x && line.e.x <= c.x && line.e.y >= c.y && line.e.y <= a.y &&   //判断线段是否在矩形内部
				line.s.x >= a.x && line.s.x <= c.x && line.s.y >= c.y && line.s.y <= a.y) {
				printf("T\n");
				continue;
			}
			if(	Intersection(line.s, line.e, a, b) || 
				Intersection(line.s, line.e, b, c) || 
				Intersection(line.s, line.e, c, d) ||
				Intersection(line.s, line.e, d, a)) {
				printf("T\n");
				continue;	
			}
			printf("F\n");
		}
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值