【计算几何】Circle VS Triangle

描述

Given a circle and a triangle, please judge whether the circle is inside the triangle or not?

输入

There are multiple cases.
The first line of each case contains six integers x1, y1, x2, y2, x3 and y3, where (x1, y1), (x2, y2) and (x3, y3) indicate the three non-collinear points of the triangle.
The next line contains three integers cx, cy and r, where (cx, cy) and r indicate the center and radius of the circle. The absolute value of each integer in this problem is no larger than 10000, and the radius of the circle is positive.

The inputs are ended with End of File. If you have some questions, please visit the help page.

输出

Each case outputs “YES” if the circle is inside ( or internally tangent to one of an edge of ) the triangle and “NO” otherwise.

样例输入

0 0 0 10 10 0
1 1 1
0 0 0 10 10 0
2 2 3

样例输出

YES
NO

思路:
第一步-使用叉积判断圆心是否在三角形内(包括边上);
第二步-计算圆心到三角形三条边的最短距离,判断是否都大于等于半径。

#include<bits/stdc++.h>
using namespace std;
int x1,Y1,x2,y2,x3,y3;
int cx,cy,r;
int cross(int ax,int ay,int bx,int by,int cx,int cy)
{
    return (bx-ax)*(cy-ay)-(by-ay)*(cx-ax);
}
bool toLeft(int ax,int ay,int bx,int by,int cx,int cy)
{
    return cross(ax,ay,bx,by,cx,cy)>0;
}
bool inTriangle()
{
    bool res=toLeft(x1,Y1,x2,y2,cx,cy);
    if (res!=toLeft(x2,y2,x3,y3,cx,cy))
    {
        return false;
    }
    if (res!=toLeft(x3,y3,x1,Y1,cx,cy))
    {
        return false;
    }
    if (cross(x1,Y1,x2,y2,x3,y3)==0)
    {
        return false;
    }
    return true;
}
double PointToSegDist(int x, int y, int ax, int ay, int bx, int by)
{
double Cross = (bx - ax) * (x - ax) + (by - ay) * (y - ay);
if (Cross <= 0) return sqrt((x - ax) * (x - ax) + (y - ay) * (y - ay));

double d2 = (bx - ax) * (bx - ax) + (by - ay) * (by - ay);
if (Cross >= d2) return sqrt((x - bx) * (x - bx) + (y - by) * (y - by));

double r = Cross / d2;
double px = ax + (bx - ax) * r;
double py = ay + (by - ay) * r;
return sqrt((x - px) * (x - px) + (py - y) * (py - y));
}
int main()
{
    while(~scanf("%d%d%d%d%d%d%d%d%d",&x1,&Y1,&x2,&y2,&x3,&y3,&cx,&cy,&r))
    {
        if (inTriangle())
        {
            double d1=PointToSegDist(cx,cy,x1,Y1,x2,y2);
            double d2=PointToSegDist(cx,cy,x1,Y1,x3,y3);
            double d3=PointToSegDist(cx,cy,x2,y2,x3,y3);
            //cout<<d1<<' '<<d2<<' '<<d3<<endl;
            if (d1>=r&&d2>=r&&d3>=r)
            {
                cout<<"YES"<<endl;
            }
            else
            {
                cout<<"NO"<<endl;
            }
        }
        else
        {
            cout<<"NO"<<endl;
        }
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值