三分套三分模板
貌似只要是单峰函数就可以用三分求解
1 #include<stdio.h> 2 #include<string.h> 3 #include<algorithm> 4 #include<math.h> 5 #define eps 1e-9 6 using namespace std; 7 struct node{ 8 double x,y; 9 }a,b,c,d; 10 double p,q,r; 11 12 inline node get(node a, node b, double p){ 13 node ans; 14 ans.x=a.x+(b.x-a.x)*p; 15 ans.y=a.y+(b.y-a.y)*p; 16 return ans; 17 } 18 19 inline double dist(node x, node y){ 20 return sqrt((x.x-y.x)*(x.x-y.x)+(x.y-y.y)*(x.y-y.y)); 21 } 22 23 inline double calc(node x, node y){ 24 return dist(a,x)/p+dist(x,y)/r+dist(y,d)/q; 25 } 26 27 inline double solve(node t){ 28 double l=0.0,r=1.0,ans; 29 while (fabs(l-r)>eps){ 30 double m1=l+(r-l)*1.0/3, m2=m1+(r-l)*1.0/3; 31 node x=get(c,d,m1), y=get(c,d,m2); 32 if (calc(t,x)<calc(t,y)) ans=m1,r=m2; else ans=m2, l=m1; 33 } 34 node x=get(c,d,ans); 35 return calc(t,x); 36 } 37 38 int main(){ 39 scanf("%lf%lf%lf%lf", &a.x, &a.y, &b.x, &b.y); 40 scanf("%lf%lf%lf%lf", &c.x, &c.y, &d.x, &d.y); 41 scanf("%lf%lf%lf", &p, &q, &r); 42 double l=0.0,r=1.0,ans; 43 while (fabs(l-r)>eps){ 44 double m1=l+(r-l)*1.0/3, m2=m1+(r-l)*1.0/3; 45 node x=get(a,b,m1), y=get(a,b,m2); 46 if (solve(x)<solve(y)) ans=m1,r=m2; else ans=m2,l=m1; 47 } 48 node x=get(a,b,ans); 49 printf("%.2lf ", solve(x)); 50 return 0; 51 }