何时使用
二分法使用的前提为一个有序的序列,可以看成只能用作单调函数,但当我们需要处理既有递增又有递减的函数,我们就可以使用三分法。
三分查找原理
对于二分法我们每次取一个mid,而对于三分法我们每次取一个mid1和mid2,这两个mid由mid - eps和mid + eps得到。我们要求一个极小值点的x,对于一个先递减再递增的区间,当mid1和mid2为F(mid - eps) > F(mid + eps)的时候,说明他在极值点的左边,所以缩小区间让l = mid,反之相同
代码实现
#include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> PII;
typedef long long ll;
typedef unsigned long long ull;
#define FAST ios::sync_with_stdio(0), cin.tie(0), cout.tie(0)
#define rep(i, a, n) for (int i = a; i <= n; i++)
#define per(i, n, a) for (int i = n; i >= a; i--)
#define mem(a,x) memset(a,x,sizeof(a))
#define all(x) (x).begin(), (x).end()
#define pb push_back
#define fi first
#define se second
#define INF 0x3f3f3f3f
#define int long long
const int mod1 = 1e9 + 7, mod2 = 998244353;
const int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0};
const int N = 20 + 5, M = 2e5 + 5;
inline int read(){
char c=getchar();int x=0,f=1;
while(c<'0'||c>'9'){if(c=='-')f=-1;c=getchar();}
while(c>='0'&&c<='9'){x=x*10+c-'0';c=getchar();}
return x*f;
}
const double eps = 1e-6;
int n;
double l, r;
double s[N];
double F(double x){ // 计算多项式
double sum = 0;
double now = 1;
per(i, n + 1, 1){
sum += now * s[i];
now *= x;
}
return sum;
}
signed main(){
// FAST;
cin >> n;
cin >> l >> r;
rep(i, 1, n + 1) cin >> s[i];
while(abs(r - l) >= eps){
double mid = (l + r) / 2;
if(F(mid - eps) >= F(mid + eps)) r = mid;
else l = mid;
}
printf("%.5f", l);
return 0;
}
三分答案
double lx = ax, ly = ay, rx = bx, ry = by;
while(dis(lx, ly, rx, ry) > eps){
double midx = (rx - lx) * 1.0 / 3, midy = (ry - ly) * 1.0 / 3;
double lmidx = midx + lx, lmidy = midy + ly, rmidx = rx - midx , rmidy = ry - midy;
double d = funF(lmidx, lmidy) + dis(lmidx, lmidy, ax, ay) * 1.0 / p;
double dd = funF(rmidx, rmidy) + dis(rmidx, rmidy, ax, ay) * 1.0 / p;
if(dd - d <= eps) lx = lmidx, ly = lmidy;
else rx = rmidx, ry = rmidy;
}