Fish’s mission
Fish’s mission 也就是求一个坐标到各个食堂的距离和最小,随机化做应该也是可以的。标程用的方法是利用单调性,不断尝试四个方向,二分的方法做的。实际上就是蚁群退火算法。
1 #include <cmath> 2 #include <cstdio> 3 #define pi acos(-1.0) 4 5 struct Point{ 6 double x,y; 7 Point(){} 8 Point(double a,double b){ 9 x=a,y=b; 10 } 11 }point[101]; 12 13 double pt_distance(const Point &p1,const Point &p2){ 14 return sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y)); 15 } 16 17 double get_all_dis(const Point &p,int n){ 18 double ans=0.0; 19 for (int i=0; i<n; i++) ans+=pt_distance(point[i],p); 20 return ans; 21 } 22 23 int main() { 24 int n; 25 while (~scanf("%d",&n)){ 26 for (int i=0; i<n; i++) 27 scanf("%lf%lf",&point[i].x,&point[i].y); 28 Point st=point[0]; 29 double step=100,mind=get_all_dis(st,n); 30 while (step>0.0002){ 31 int ok=1; 32 while (ok){ 33 Point tmp,nt; 34 double t; 35 ok=0,nt=st; 36 37 tmp=Point(st.x,st.y+step); 38 t=get_all_dis(tmp,n); 39 if (t<mind) mind=t,ok=1,nt=tmp; 40 41 tmp=Point(st.x,st.y-step); 42 t=get_all_dis(tmp,n); 43 if (t<mind) mind=t,ok=1,nt=tmp; 44 45 tmp=Point(st.x+step,st.y); 46 t=get_all_dis(tmp,n); 47 if (t<mind) mind=t,ok=1,nt=tmp; 48 49 tmp=Point(st.x-step,st.y); 50 t=get_all_dis(tmp,n); 51 if (t<mind) mind=t,ok=1,nt=tmp; 52 53 st=nt; 54 } 55 step=step/2.0; 56 } 57 printf("%.3lf\n",mind); 58 } 59 return 0; 60 }