buaa 1033 easy problom(三分搜索)
三分搜索第一题纪念
三分搜索对于凹凸函数极值非常有效
#include<stdio.h> #include<math.h> #define eps 0.00000001 struct node { double x,y,z; }; double dist(node a,node b) { return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y)+(a.z-b.z)*(a.z-b.z)); } int main() { int cs,p=1;scanf("%d",&cs); while(p<=cs) { node p1,p2,s,e,d; scanf("%lf%lf%lf",&d.x,&d.y,&d.z); scanf("%lf%lf%lf",&s.x,&s.y,&s.z); scanf("%lf%lf%lf",&e.x,&e.y,&e.z); while(dist(s,e)>eps) { node p1,p2; p1.x=(s.x+e.x)/2; p1.y=(s.y+e.y)/2; p1.z=(s.z+e.z)/2; double d1=dist(p1,d); p2.x=(p1.x+e.x)/2; p2.y=(p1.y+e.y)/2; p2.z=(p1.z+e.z)/2; double d2=dist(p2,d); if(d1<d2) e=p2; else s=p1; } printf("Case %d: %.2f\n",p++,dist(e,d)); } }
Just a little, maybe change the world