The big cake can be considered as a circle on a 2D plane. The ant’s home can be considered as a rectangle. The ant can walk through the cake. Please find out the shortest path for the poor ant.
InputThe input consists of several test cases.
The first line of each test case contains x,y, representing the coordinate of the starting point. The second line contains x, y, r. The center of the cake is point (x,y) and the radius of the cake is r. The third line contains x1,y1,x2,y2, representing the coordinates of two opposite vertices of the rectangle --- the ant's home.
All numbers in the input are real numbers range from -10000 to 10000. It is guaranteed that the cake and the ant's home don't overlap or contact, and the ant's starting point also is not inside the cake or his home, and doesn't contact with the cake or his home.
If the ant touches any part of home, then he is at home.
Input ends with a line of 0 0. There may be a blank line between two test cases.OutputFor each test case, print the shortest distance to achieve his goal. Please round the result to 2 digits after decimal point.Sample Input
1 1 -1 1 1 0 -1 1 0 0 2 -1 1 1 0 -1 1 0 0 0
Sample Output
1.75 2.00
这是道好题啊。
题意:给定一点,一圆,一矩形(三者互不包含),求从点到圆再到矩形的最短路径。
解题思路:先求出点到矩形最近的点,再求圆到这条直线最近的那个点,将这三点连到一块就是答案。
两种解法,一种是直接枚举圆周上的点,二是三分。
枚举圆周ac代码:
1 #include <cstdio> 2 #include <iostream> 3 #include <cmath> 4 #include <string> 5 #include <cstring> 6 #include <algorithm> 7 #include <iomanip> 8 using namespace std; 9 typedef long long ll; 10 const double inf = 111111; 11 const double pi=acos(-1.0); 12 const double eps = 1e-6; 13 struct nod{ 14 double x; 15 double y; 16 }bg,rec[5],pt,q,rel,rer; 17 double r; 18 double getd(nod a,nod b) 19 { 20 double dis=sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y)); 21 return dis; 22 } 23 double getdis(nod p,nod a,nod b)//因为点不会在矩形内,所以只需要根据对角线的这两点判断即可。 24 { 25 double xx=0,yy=0; 26 if(p.x<a.x) xx=a.x-p.x; 27 else if(p.x>b.x) xx=p.x-b.x; 28 if(p.y<a.y) yy=a.y-p.y; 29 else if(p.y>b.y) yy=p.y-b.y; 30 return sqrt(xx*xx+yy*yy); 31 } 32 int main() { 33 ios::sync_with_stdio(false); 34 cout<<setiosflags(ios::fixed)<<setprecision(2); 35 while(cin>>bg.x>>bg.y) 36 { 37 if(fabs(bg.x)<eps&& fabs(bg.y)<eps) break; 38 cin>>pt.x>>pt.y>>r; 39 for(int i=0;i<2;++i) 40 { 41 cin>>rec[i].x>>rec[i].y; 42 } 43 rel.x=min(rec[0].x,rec[1].x);//把点换为(x,y)最小的与最大的两个点。 44 rel.y=min(rec[0].y,rec[1].y); 45 rer.x=max(rec[0].x,rec[1].x); 46 rer.y=max(rec[0].y,rec[1].y); 47 double ans=inf*1.0; 48 for(double dre=0;dre<360.0;dre+=0.01)//枚举圆周上的点 49 { 50 q.x=pt.x+cos(dre/180*pi)*r; 51 q.y=pt.y+sin(dre/180*pi)*r; 52 ans=min(ans,getdis(q,rel,rer)+getd(q,bg)); 53 } 54 cout<<setprecision(2)<<ans<<endl; 55 } 56 return 0; 57 }
参考博客:https://www.cnblogs.com/shu-xiaohao/p/3385065.html