题目链接: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; }