-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathTernary Search
43 lines (35 loc) · 1.01 KB
/
Ternary Search
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/// learnt from https://codeforces.com/contest/394/submission/13185760
long double dist=1e100 ;
Point nw=rp ;
for(int i=0;i<m;++i){
long double l=0 , r=1 , m1 , m2 ;
for(int it=1;it<=100;++it){
m1=l*.51+r*.49 ;
m2=l*.49+r*.51 ;
Point p1=yo[i]+(yo[i+1]-yo[i])*m1 ;
Point p2=yo[i]+(yo[i+1]-yo[i])*m2 ;
long double v1=(p1-rp).dis() ;
long double v2=(p2-rp).dis() ;
if(v1<v2)
r=m2 ;
else
l=m1 ;
}
Point now=yo[i]+(yo[i+1]-yo[i])*(l+r)*.5 ;
if((now-rp).dis()<dist)
dist=(now-rp).dis() , nw=now ;
}
/// learnt from https://codeforces.com/contest/98/submission/57618653
double ternary_search(double lo,double hi){
while(lo+EPS<=hi){
double m1=(lo*2.0+hi)/3.0 ;
double m2=(lo+hi*2.0)/3.0 ;
double v1=val(m1) ;
double v2=val(m2) ;
if(v1<v2)
hi=m2 ;
else
lo=m1 ;
}
return val((lo+hi)/2.0) ;
}