题意:判断一线段与矩形是否相交。需要注意的是输入可能不是按照左上右下的顺序,如果线段两个端点都在举行内的话也算相交。
这题分为判断线段与4边是否有交点,如果没有判断两点是否在矩形内就可以了。我用的方法是射线法。
#include <iostream> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; typedef double PointType; struct point { PointType x,y; }; PointType Direction(point pi,point pj,point pk) //判断向量PiPj在向量PiPk的顺逆时针方向 +顺-逆0共线 { return (pj.x-pi.x)*(pk.y-pi.y)-(pk.x-pi.x)*(pj.y-pi.y); } bool On_Segment(point pi,point pj,point pk) { if(pk.x>=min(pi.x,pj.x)&&pk.x<=max(pi.x,pj.x)&&pk.y>=min(pi.y,pj.y)&&pk.y<=max(pi.y,pj.y)) return 1; return 0; } bool Segment_Intersect(point p1,point p2,point p3,point p4) { PointType d1=Direction(p3,p4,p1),d2=Direction(p3,p4,p2),d3=Direction(p1,p2,p3),d4=Direction(p1,p2,p4); if(((d1>0&&d2<0)||(d1<0&&d2>0))&&((d3>0&&d4<0)||(d3<0&&d4>0))) return 1; if(d1==0&&On_Segment(p3,p4,p1)) return 1; if(d2==0&&On_Segment(p3,p4,p2)) return 1; if(d3==0&&On_Segment(p1,p2,p3)) return 1; if(d4==0&&On_Segment(p1,p2,p4)) return 1; return 0; } int Pandingdian(point a,int n,point *polygon)//1在多边形上 2在多边形外 0在多边形内 { point b; b.x=-9999999; b.y=a.y; int sum=0;polygon[n]=polygon[0]; for(int i=1; i<=n; i++) if(polygon[i].y-polygon[i-1].y!=0&&Segment_Intersect(a,b,polygon[i],polygon[i-1])) { if(Direction(a,polygon[i],polygon[i-1])==0) return 1; sum++; } if(sum&1) return 0; return 2; } int main() { point a,b,lt,rb,lb,rt,polygon[10]; int n; scanf("%d",&n); while(n--) { scanf("%lf%lf%lf%lf%lf%lf%lf%lf",&a.x,&a.y,&b.x,&b.y,<.x,<.y,&rb.x,&rb.y); if(lt.x>rb.x) swap(lt.x,rb.x); if(lt.y<rb.y) swap(lt.y,rb.y); rt.x=rb.x,rt.y=lt.y; lb.x=lt.x,lb.y=rb.y; polygon[0]=lb,polygon[1]=rb,polygon[2]=rt,polygon[3]=lt,polygon[4]=lb; int ans=0; for(int i=1;i<5;i++) if(Segment_Intersect(a,b,polygon[i],polygon[i-1])) { puts("T"),ans=1; break; } if(ans) continue; if(Pandingdian(a,4,polygon)==0&&Pandingdian(b,4,polygon)==0) { puts("T"); continue; } puts("F"); } return 0; }
时间: 2024-10-31 22:58:56