HDU 1221 Rectangle and Circle(判定圆与矩形是否相交)
http://acm.hdu.edu.cn/showproblem.php?pid=1221
题意:
给你一个圆和一个矩形,要你判断它们是否相交?(就算只有一个公共点也算相交)
分析:
我们只要求出圆心到矩形的最短距离L和圆心到矩形的最长距离R.
如果L>r(r为圆半径),圆肯定与矩形不相交.
如果R<r,圆包含了矩形,依然与矩形不相交.
如果L<=r且R>=r,那么圆肯定与矩形相交.
(想想为什么是上面三种情况)
下面的问题是如何求圆心到矩形的最小最大距离呢? 圆心到矩形的距离一定是圆心到矩形的4条线段(边)的距离.所以我们只需要求出圆心到矩形4边(线段)的最小距离,就可以得到L.
圆心到矩形最大距离依然是圆心到矩形4边的最大距离,该距离一定只在4条线段的端点产生.所以我们只要求圆心到矩形4个顶点的端点距离即可.
AC代码:
#include<cstdio> #include<cstring> #include<algorithm> #include<cmath> using namespace std; const double eps=1e-10; int dcmp(double x) { if(fabs(x)<eps) return 0; return x<0?-1:1; } struct Point { double x,y; Point(){} Point(double x,double y):x(x),y(y){} }; typedef Point Vector; Vector operator-(Point A,Point B) { return Vector(A.x-B.x,A.y-B.y); } bool operator==(Vector A,Vector B) { return dcmp(A.x-B.x)==0 && dcmp(A.y-B.y)==0; } double Dot(Vector A,Vector B) { return A.x*B.x+A.y*B.y; } double Length(Vector A) { return sqrt(Dot(A,A)); } double Cross(Vector A,Vector B) { return A.x*B.y-A.y*B.x; } void DistanceToSegment(Point P,Point A,Point B,double &L,double &R) { if(A==B) R=L=Length(P-A);//R返回点P到线段的最大距离,L返回最小距离 else { Vector v1=B-A,v2=P-A,v3=P-B; if(dcmp(Dot(v1,v2))<0) L=Length(v2); else if(dcmp(Dot(v1,v3))>0) L=Length(v3); else L= fabs(Cross(v1,v2))/Length(v1); R=max(Length(v2), Length(v3)); } } int main() { int T; scanf("%d",&T); while(T--) { double x,y,r,x1,y1,x2,y2; scanf("%lf%lf%lf%lf%lf%lf%lf",&x,&y,&r,&x1,&y1,&x2,&y2); if(x1>x2) swap(x1,x2); if(y1>y2) swap(y1,y2); Point p[4],c(x,y);//p[4]是矩形的4个点,c是圆心 p[0]=Point(x1,y1); p[1]=Point(x2,y1); p[2]=Point(x2,y2); p[3]=Point(x1,y2); double min_dist=1e10,max_dist=-1e10; for(int i=0;i<4;++i) { double L,R; DistanceToSegment(c,p[i],p[(i+1)%4],L,R); min_dist=min(min_dist,L); max_dist=max(max_dist,R); } if(dcmp(min_dist-r)>0 || dcmp(r-max_dist)>0 ) printf("NO\n"); else printf("YES\n"); } return 0; }