[POJ1410]Intersection(计算几何)

本文介绍了一种判断线段与矩形是否有公共点的方法。通过检查线段与矩形四条边的相交情况及线段端点是否位于矩形内部来实现碰撞检测。代码使用C++实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

传送门
题意:给出一条线段和一个矩形,判断它们是否有公共点

题解

先判断线段和矩形的每一条边是否相交
然后再判断线段是否在矩形内部
由于是一个简单的矩形不是多边形只需要判断坐标范围就行了
矩形的坐标给出的是无序的,需要自己排序

代码

#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
using namespace std;

const double eps=1e-9;
int dcmp(double x)
{
    if (x<=eps&&x>=-eps) return 0;
    return (x>0)?1:-1;
}
struct Vector
{
    double x,y;
    Vector(double X=0,double Y=0)
    {
        x=X,y=Y;
    }
};
typedef Vector Point;
struct Line
{
    Point p,q;
    Line(Point P=Point(0,0),Point Q=Point(0,0))
    {
        p=P,q=Q;
    }
};
Vector operator - (Vector A,Vector B) {return Vector(A.x-B.x,A.y-B.y);}
int T;
Point A,B;
Line l,m;
double a,b,c,d;
bool flag;

double Dot(Vector A,Vector B)
{
    return A.x*B.x+A.y*B.y;
}
double Cross(Vector A,Vector B)
{
    return A.x*B.y-A.y*B.x;
}
bool check(Line l,Line m)
{
    bool flag=true;
    Vector u,v,w;
    int x,y;
    u=l.p-l.q;v=m.p-l.q;w=m.q-l.q;
    x=dcmp(Cross(u,v));y=dcmp(Cross(u,w));
    if ((x==y&&x)||(!x&&!y&&dcmp(Dot(v,w))>=0)) flag=false;
    u=m.p-m.q;v=l.p-m.q;w=l.q-m.q;
    x=dcmp(Cross(u,v));y=dcmp(Cross(u,w));
    if ((x==y&&x)||(!x&&!y&&dcmp(Dot(v,w))>=0)) flag=false;
    return flag;
}
bool PInP(Point P,double a,double b,double c,double d)
{
    return dcmp(P.x-a)>=0&&dcmp(P.x-c)<=0&&dcmp(P.y-b)>=0&&dcmp(P.y-d)<=0;
}
int main()
{
    scanf("%d",&T);
    while (T--)
    {
        flag=false;
        scanf("%lf%lf%lf%lf",&a,&b,&c,&d);
        A=Point(a,b),B=Point(c,d);
        l=Line(A,B);
        scanf("%lf%lf%lf%lf",&a,&b,&c,&d);
        if (dcmp(a-c)>0) swap(a,c);
        if (dcmp(b-d)>0) swap(b,d);
        m=Line(Point(a,b),Point(a,d));
        flag|=check(l,m);
        m=Line(Point(a,b),Point(c,b));
        flag|=check(l,m);
        m=Line(Point(c,d),Point(a,d));
        flag|=check(l,m);
        m=Line(Point(c,d),Point(c,b));
        flag|=check(l,m);
        if (flag) puts("T");
        else
        {
            if (PInP(A,a,b,c,d)&&PInP(B,a,b,c,d)) puts("T");
            else puts("F");
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值