1. 程式人生 > >hdu 1221 Rectangle and Circle(判斷矩形與圓是否相交)

hdu 1221 Rectangle and Circle(判斷矩形與圓是否相交)

題目有點坑,坑了我好多點,由於自己考慮問題的方面不是很全,沒有找到一個科學的判斷方法,會漏判好多情況

自己ac了此題之後,看了下別人的部落格思路

大致如下:

分析:

       我們只要求出圓心到矩形的最短距離L和圓心到矩形的最長距離R.

如果L>r(r為圓半徑),圓肯定與矩形不相交.

如果R<r,圓包含了矩形,依然與矩形不相交.

如果L<=r且R>=r,那麼圓肯定與矩形相交.

 

自己ac的程式碼:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<cmath>
#include<algorithm>
#include <vector>
#include<queue>
#include <stack>
#include <map>
#define maxn 34005
#define INF 0x3f3f3f3f
#define LL long long
using namespace std;

int t;
double xc,yc,r;
double xt_a,yt_a,xt_b,yt_b;
double dis(double a,double b,double x,double y)
{
   return (a-x)*(a-x)+(b-y)*(b-y);
}
bool judge()
{
   double ctopx=xc;
   double ctopy=yc+r;
   double cleftx=xc-r;
   double clefty=yc;
   double crightx=xc+r;
   double crighty=yc;
   double clowx=xc;
   double clowy=yc-r;
   double xt_c,yt_c,xt_d,yt_d;
   xt_c=xt_a;yt_c=yt_b;
   xt_d=xt_b;yt_d=yt_a;
   if(yt_a>ctopy&&yt_b>ctopy&&yt_c>ctopy&&yt_d>ctopy)
      return false;
   if(yt_a<clowy&&yt_b<clowy&&yt_c<clowy&&yt_d<clowy)
      return false;
   if(xt_a>crightx&&xt_b>crightx&&xt_c>crightx&&xt_d>crightx)
      return false;
   if(xt_a<cleftx&&xt_b<cleftx&&xt_c<cleftx&&xt_d<cleftx)
      return false;
   //圓在矩形裡頭
   if(fabs(xt_a-xc)>r&&fabs(xt_b-xc)>r&&fabs(yt_a-yc)>r&&fabs(yt_b-yc)>r)
      return false;
   //矩形在圓形裡頭
   if(dis(xt_a,yt_a,xc,yc)<r*r&&dis(xt_b,yt_b,xc,yc)<r*r&&dis(xt_c,yt_c,xc,yc)<r*r&&dis(xt_d,yt_d,xc,yc)<r*r)
      return false;
   //圓形覆蓋了矩形兩條邊界
   if(yt_a>clowy&&yt_b<ctopy||xt_a>cleftx&&xt_b<crightx)
      return true;
   //此矩形的一個頂點在,在對應此內切圓的正方形內,但不在圓內的區域
   if(dis(xt_a,yt_a,xc,yc)>r*r&&dis(xt_b,yt_b,xc,yc)>r*r&&dis(xt_c,yt_c,xc,yc)>r*r&&dis(xt_d,yt_d,xc,yc)>r*r)
      return false;
   return true;
}
int main()
{
    ios::sync_with_stdio(false);
    cin>>t;
    while(t--)
    {
       cin>>xc>>yc>>r>>xt_a>>yt_a>>xt_b>>yt_b;
       if(judge())
         cout << "YES\n";
       else
         cout << "NO\n";
    }

    return 0;
}