描述
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;
}