1. 程式人生 > >POJ 1410 判斷線段與矩形交點或在矩形內

POJ 1410 判斷線段與矩形交點或在矩形內

ios bsp math turn ++ open 坐標 順序 main

這個題目要註意的是:給出的矩形坐標不一定是按照左上,右下這個順序的

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#define eps 1e-8
#define INF 1e9
using namespace std;

const int maxn=100;

typedef struct Point
{
    double x,y;
    Point() {};
    Point(
double xx,double yy) { x=xx; y=yy; } } Vector; struct Line { Point p,q; Line() {}; Line(Point pp,Point qq) { p=pp; q=qq; } }; int sgn(double x) { if(fabs(x)<eps) return 0; return x<0? -1:1; } double crs_prdct(Vector a,Vector b) {
return a.x*b.y-b.x*a.y; } double dot_prdct(Vector a,Vector b) { return a.x*a.y+b.x*b.y; } Vector operator - (Point a,Point b) { return Vector(a.x-b.x,a.y-b.y); } //判斷點在線段上 bool OnSeg(Point P,Line L) { return sgn(crs_prdct(L.p-P,L.q-P))== 0&& sgn((P.x
-L.p.x)*(P.x-L.q.x))<= 0 && sgn((P.y-L.p.y)*(P.y-L.q.y))<= 0; } //-1:點在凸多邊形外 //0:點在凸多邊形邊界上 //1:點在凸多邊形內 int inConvexPoly(Point a,Point p[],int n) { for(int i = 0; i < n; i++) { if(sgn(crs_prdct(p[i]-a,p[(i+1)%n]-a)) < 0)return -1; else if(OnSeg(a,Line(p[i],p[(i+1)%n])))return 0; } return 1; } bool inter(Line l1,Line l2) { return max(l1.p.x,l1.q.x) >= min(l2.p.x,l2.q.x) && max(l2.p.x,l2.q.x) >= min(l1.p.x,l1.q.x) && max(l1.p.y,l1.q.y) >= min(l2.p.y,l2.q.y) && max(l2.p.y,l2.q.y) >= min(l1.p.y,l1.q.y) && sgn(crs_prdct(l2.p-l1.p,l1.q-l1.p))*sgn(crs_prdct(l2.q-l1.p,l1.q-l1.p))<=0 && sgn(crs_prdct(l1.p-l2.p,l2.q-l1.p))*sgn(crs_prdct(l1.q-l2.p,l2.q-l2.p))<=0; } int main() { // freopen("in.txt","r",stdin); int t; scanf("%d",&t); Point pot[10]; while(t--) { double x1,y1,x2,y2; scanf("%lf%lf%lf%lf",&x1,&y1,&x2,&y2); Line li=Line(Point(x1,y1),Point(x2,y2)); scanf("%lf%lf%lf%lf",&x1,&y1,&x2,&y2); if(x1 > x2)swap(x1,x2); if(y1 > y2)swap(y1,y2); pot[0]=Point(x1,y1); pot[1]=Point(x2,y1); pot[2]=Point(x2,y2); pot[3]=Point(x1,y2); if(inConvexPoly(li.p,pot,4)>=0 || inConvexPoly(li.q,pot,4)>=0) { puts("T"); continue; } bool flag=false; for(int i=0; i<4; i++) { if(inter(li,Line(pot[i],pot[(i+1)%4]))) { flag=true; break; } } puts(flag? "T":"F"); } return 0; }

POJ 1410 判斷線段與矩形交點或在矩形內