三分

单峰函数求极值。

取两个三等分点,如果是求极大值,那么较小的那端调整。

如果求极小值,那么较大的那端调整。

类似于爬坡过程,让离极值更远的一端爬到三等分点。

例题:P3382 三分

参考代码
#include <cstdio>
const int N = 15;
const double EPS = 1e-6;
int n;
double a[N];
double calc(double x) {
double res = 0;
for (int i = n; i >= 0; i--) {
res = res * x + a[i];
}
return res;
}
int main()
{
double l, r; scanf("%d%lf%lf", &n, &l, &r);
for (int i = n; i >= 0; i--) scanf("%lf", &a[i]);
while (r - l > EPS) {
double k = (r - l) / 3;
double mid1 = l + k, mid2 = r - k;
if (calc(mid1) > calc(mid2)) r = mid2;
else l = mid1;
}
printf("%.5f\n", l);
return 0;
}

习题:P1883 【模板】三分 | 函数

解题思路

F(x) 依然是一个单谷函数(高中数学必修 1),可以用三分法。

参考代码
#include <cstdio>
#include <cmath>
const int N = 10005;
int n, a[N], b[N], c[N];
double calc(double x) {
double res = 0;
for (int i = 1; i <= n; i++) {
double f = a[i] * x * x + b[i] * x + c[i];
if (i == 1) res = f;
else if (f > res) res = f;
}
return res;
}
void solve() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) scanf("%d%d%d", &a[i], &b[i], &c[i]);
double l = 0, r = 1000;
for (int i = 1; i <= 100; i++) {
double k = (r - l) / 3;
double mid1 = l + k, mid2 = r - k;
if (calc(mid1) > calc(mid2)) l = mid1;
else r = mid2;
}
printf("%.4f\n", calc(l));
}
int main()
{
int t; scanf("%d", &t);
for (int i = 1; i <= t; i++) solve();
return 0;
}
posted @   RonChen  阅读(20)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 【杂谈】分布式事务——高大上的无用知识?
点击右上角即可分享
微信分享提示