Intersection - POJ 1410(线段与矩形是否相交)

题目大意:给一个线段和一个矩形,判断线段是否和矩形有公共点。
 
分析:用矩形的四个边当线段判断与所给的线段是否有交点,需要注意的是给的矩形是不标准的,需要自己转换,还需要注意线段有可能在矩形内部。
 
代码如下:
===============================================================================================================================================
#include<stdio.h>
#include<math.h>
#include<algorithm>
using namespace std;

const int MAXN = 1e3+7;
const int oo = 1e9+7;
const double EPS = 1e-12;

struct point
{
    double x, y;
    point(double x=0, double y=0):x(x), y(y){}
    point operator - (const point &t) const{
        return point(x-t.x, y-t.y);
    }
    int operator * (const point &t) const{
        double ans = x*t.y - y*t.x;

        if(ans > EPS)return 1;
        if(fabs(ans) < EPS)return 0;
        return -1;
    }
};
struct segment
{
    point A, B;
    segment(point A=0, point B=0):A(A), B(B){}
    bool Intersect(const segment &t)const{
        int t1 = (A-B) * (t.A-B);
        int t2 = (A-B) * (t.B-B);

        if(t1==0 && t.A.x>=min(A.x, B.x) && t.A.x <= max(A.x, B.x)
           && t.A.y>=min(A.y, B.y) && t.A.y <= max(A.y, B.y))return true;
        if(t2==0 && t.B.x>=min(A.x, B.x) && t.B.x <= max(A.x, B.x)
           && t.B.y>=min(A.y, B.y) && t.B.y <= max(A.y, B.y))return true;
        if(t1==0&&t2==0 && max(t.A.x,t.B.x)>=max(A.x,B.x) &&min(t.A.x,t.B.x)<=min(A.x,B.x)
           && max(t.A.y,t.B.y)>=max(A.y,B.y) &&min(t.A.y,t.B.y)<=min(A.y,B.y) )return true;
        if(t1*t2 == -1)return true;

        return false;
    }
};
bool Find(segment a, segment sg[], int N)
{
    for(int i=0; i<N; i++)
    {
        if(a.Intersect(sg[i]) && sg[i].Intersect(a))
            return true;
    }

    return false;
}

int main()
{
    int T, t=1;

    scanf("%d", &T);

    while(T--)
    {
        segment a, sg[10];
        point A, B;

        scanf("%lf%lf%lf%lf", &a.A.x, &a.A.y, &a.B.x, &a.B.y);
        scanf("%lf%lf%lf%lf", &A.x, &A.y, &B.x, &B.y);

        if(A.x > B.x)swap(A.x, B.x);
        if(A.y < B.y)swap(A.y, B.y);

        sg[0] = segment(A, point(A.x, B.y));
        sg[1] = segment(A, point(B.x, A.y));
        sg[2] = segment(B, point(A.x, B.y));
        sg[3] = segment(B, point(B.x, A.y));

       /// printf("Case %d: ", t++);
        if(Find(a, sg, 4) == true || (a.A.x>=A.x&&a.A.x<=B.x && a.A.y>=B.y && a.A.y <= A.y) )
            printf("T\n");
        else
            printf("F\n");
    }

    return 0;
}
/**
2
4 2 4 0 4 3 9 6
**/

 

posted @ 2015-09-08 22:17  无忧望月  阅读(170)  评论(0编辑  收藏  举报
levels of contents