您的位置:首页 > 其它

51nod 1298 圆与三角形

2015-04-02 22:44 309 查看
给出圆心、三角形三点坐标,以及圆的半径,判断圆与三角形是否相交。



我是由两点的坐标求直线方程,然后和圆联立方程组,看是否有交点,如果有,并且交点应当在给出的两点之间,则相交。

也许还有更好的方法。



#include<cstdio>
#include<cmath>
#include<algorithm>
using namespace std;
struct P
{
    double x,y;
};
struct circle
{
    P c;
    double r;
};

int cmp(double x)
{
        if(fabs(x)<1e-15) return 0;
        if(x>0) return 1;
        return -1;
}

bool judge(double a,double b,double c,double &x1,double &x2)
{
    double tep=b*b-4*a*c;
    if(cmp(tep)<0) return 0;
    x1=(-b+sqrt(tep))/(2*a);
    x2=(-b-sqrt(tep))/(2*a);
    return 1;
}
bool judge(circle o,P a,P c)    //线段与圆的关系
{
    double k,b;
    if(cmp(a.x-c.x)==0)
    {
        double t=o.r*o.r-(a.x-o.c.x)*(a.x-o.c.x);
        if(t<0) return 0;
        double maxy=max(a.y,c.y),miny=min(a.y,c.y),y1=sqrt(t)+o.c.y,y2=o.c.y-sqrt(t);
        if(cmp(miny-y1)<=0&&cmp(y1-maxy)<=0) return 1;
        if(cmp(miny-y2)<=0&&cmp(y2-maxy)<=0) return 1;
        return 0;
    }
    k=(a.y-c.y)/(a.x-c.x);
    b=a.y-k*a.x;
    double x1,x2;
    int f=judge(k*k+1,2*k*(b-o.c.y)-2*o.c.x,o.c.x*o.c.x+(b-o.c.y)*(b-o.c.y)-o.r*o.r,x1,x2);
    if(f==0) return 0;
    int maxx=max(a.x,c.x),minx=min(a.x,c.x);
    if(cmp(minx-x1)<=0&&cmp(x1-maxx)<=0) return 1;
    if(cmp(minx-x2)<=0&&cmp(x2-maxx)<=0) return 1;
    return 0;
}
bool judge(circle o,P a,P b,P c)
{
        if(judge(o,a,b)||judge(o,a,c)||judge(o,b,c)) return 1;
        return 0;
}

int main()
{
    int t;
    circle o;
    P a,b,c;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%lf%lf%lf",&o.c.x,&o.c.y,&o.r);
        scanf("%lf%lf%lf%lf%lf%lf",&a.x,&a.y,&b.x,&b.y,&c.x,&c.y);
        if(judge(o,a,b,c)) puts("Yes");
        else puts("No");
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: