算法与数据结构-三分

三分可以说是二分的升级版,二分是在有序数组中操作,而三分则是在单峰函数中操作。以凸函数为例,把区间三等分,L、A、B、R。当f(A)>f(B)时,就把B至R这一段舍弃掉,而当f(A)<f(B)时,就把L至A舍弃,当f(A)和f(B)相等时,就留下中间一段。

例题 luoguP3382

 1 #include<cstdio>
 2 #include<algorithm>
 3 #include<cmath>
 4 using namespace std;
 5 const double eps=1e-8;
 6 int n;
 7 double l,r,a[15];
 8 double f(double x){
 9     double now=1.0;
10     double res=0.0;
11     for (int i=0; i<=n; i++) {
12         res+=a[i]*now;
13         now*=x;
14     }
15     return res;
16 }
17 void solve(double l,double r){
18     if (r-l<eps) {
19         printf("%.5lf\n",l);
20         return;
21     }
22     double x1=l+(r-l)/3;
23     double x2=r-(r-l)/3;
24     double f1=f(x1);
25     double f2=f(x2);
26     if (f1<f2) solve(x1,r);
27     else if (f1>f2) solve(l,x2);
28     else solve(x1,x2);
29 }
30 int main(){
31     //ios::sync_with_stdio(false);
32     scanf("%d%lf%lf",&n,&l,&r);
33     for (int i=1; i<=n+1; i++) scanf("%lf",&a[n-i+1]);
34     solve(l,r);
35     return 0;
36 }

 

posted @ 2019-03-20 11:02  MoerBlack  阅读(170)  评论(0编辑  收藏  举报