POJ 1410 判断线段与矩形交点或在矩形内

这个题目要注意的是:给出的矩形坐标不一定是按照左上,右下这个顺序的

#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*b.x+a.y*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;
}

 

posted @ 2017-07-20 21:44  Pacify  阅读(644)  评论(0编辑  收藏  举报