Rectangle and Circle
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 1933 Accepted Submission(s): 451
Problem Description
Given a rectangle and a circle in the coordinate system(two edges of the rectangle are parallel with the X-axis, and the other two are parallel with the Y-axis), you have to tell if their borders intersect.
Note: we call them intersect even if they are just tangent. The circle is located by its centre and radius, and the rectangle is located by one of its diagonal.
Note: we call them intersect even if they are just tangent. The circle is located by its centre and radius, and the rectangle is located by one of its diagonal.
Input
The first line of input is a positive integer P which indicates the number of test cases. Then P test cases follow. Each test cases consists of seven real numbers, they are X,Y,R,X1,Y1,X2,Y2. That means the centre of a circle is (X,Y) and the radius of the circle is R, and one of the rectangle's diagonal is (X1,Y1)-(X2,Y2).
Output
For each test case, if the rectangle and the circle intersects, just output "YES" in a single line, or you should output "NO" in a single line.
Sample Input
2
1 1 1 1 2 4 3
1 1 1 1 3 4 4.5
Sample Output
YES
NO
Author
weigang Lee
Source
Recommend
Ignatius.L
#include<iostream> #include<algorithm> #include<cstdio> #include<cmath> using namespace std; #define eps 1e-8 struct point{ double x,y; }; double dis(point p1,point p2){ return sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y)); } double xmult(point p1,point p2,point p0){ return (p1.x-p0.x)*(p2.y-p0.y)-(p2.x-p0.x)*(p1.y-p0.y); } double distoline(point p,point l1,point l2){ return fabs(xmult(p,l1,l2)/dis(l1,l2)); } int isIntersect(point c,double r,point l1,point l2){ double t1=dis(c,l1)-r, t2=dis(c,l2)-r; point t=c; if(t1<eps || t2<eps) return t1>-eps || t2>-eps; t.x+=l1.y-l2.y; t.y+=l2.x-l1.x; return xmult(l1,c,t)*xmult(l2,c,t)<eps && distoline(c,l1,l2)-r<eps; } point p[4],cir; double X,Y,R,X1,Y1,X2,Y2; int main(){ //freopen("input.txt","r",stdin); int t; cin>>t; while(t--){ cin>>X>>Y>>R>>X1>>Y1>>X2>>Y2; p[0].x=X1; p[0].y=Y1; p[1].x=X1; p[1].y=Y2; p[2].x=X2; p[2].y=Y2; p[3].x=X2; p[3].y=Y1; cir.x=X; cir.y=Y; int flag=0; for(int i=0;i<4;i++) if(isIntersect(cir,R,p[i%4],p[(i+1)%4])){ flag=1; break; } if(flag) printf("YES\n"); else printf("NO\n"); } return 0; }