Test instructions: Whether the segment intersects the rectangle, and the segments intersect within the rectangle.
Formula: P1*p2= (X1*X2,Y1*Y2) (inner product), p1xp2= (x1*y2,x2*y1) (outer product)
Determine if q is on the line p1-p2 above, according to (P1-Q) x (p2-q) = "Q" is the linear p1-p2. Use the inner product (p1-q) * (P2-Q) <0 to determine if q is between p1-p2.
Intersection of P1-P2,Q1-Q2:
(x, Y) =p1+ (P2-P1) * ((Q2-Q1) x (Q1-P1)/((Q2-Q1) x (P2-P1)));
Note: The coordinate input of the left and lower right corner is not entered in the upper left corner and then the lower right corner, so you need to determine the coordinates of the upper-left and lower-right corners.
#include <iostream> #include <cstdio> #include <cmath>using namespace std; #define EPS 1e-10struct Point{double A, B; Point () {}-point (double a,double b): A (a), B (b) {}-operator + (point P) {return-point (P.A+A,P.B+B); } Point operator – (point P) {return point (A-P.A,B-P.B); } Point operator * (double p) {return point (a*p,b*p); } double dot (point P)//inner product {return (P.A*A+P.B*B); } double det (point P)//outer product {return (A*P.B-B*P.A); }};p oint p1,p2,q1,q2;//to determine if Q is on the segment P1-P2 bool On_str (point p1,point p2,point q) {return (ABS ((p1-q). Det (p2-q)) <eps && (p1-q) dot (p2-q) <eps);} Ask for a two-line intersection point intersection (Point P1,point p2,point q1,point Q2) {return p1+ (P2-P1) * ((Q2-Q1). Det (Q1-P1)/(Q2-Q1). Det ( P2-P1));} BOOL Judge (Point Q1,point Q2) {if (ABS ((P1-P2). Det (q1-q2)) <eps) {if (On_str (p1,p2,q1) | | On_str (P1,P2,Q2) | | On_str (Q1,Q2,P1) | | On_str (Q1,Q2,P2))//Determine if there is a coincident return 1; else return 0; } point R=intersection (P1,P2,Q1,Q2); Return On_str (p1,p2,r) &&on_str (q1,q2,r);} int main () {int n; scanf ("%d", &n); while (n--) {scanf ("%lf%lf%lf%lf%lf%lf%lf%lf", &p1.a,&p1.b,&p2.a,&p2.b,&q1.a,&q1.b,&q 2.A,&Q2.B); if (q1.a>q2.a) swap (q1.a,q2.a); if (q1.b<q2.b) swap (q1.b,q2.b); if (p1.a>=q1.a&&p1.a<=q2.a&&p1.b<=q1.b&&p1.b>=q2.b&&p2.a>=q1.a &&p2.a<=q2.a&&p2.b<=q1.b&&p2.b>=q2.b) {printf ("t\n"); } else{if (Judge (Q1,point (q2.a,q1.b)) | | Judge (Q1,point (q1.a,q2.b)) | | Judge (Q2,point (q2.a,q1.b)) | | Judge (Q2,point (q1.a,q2.b))) printf ("t\n"); else printf ("f\n"); }} return 0;}
uva191 intersection (intersection between segments)