三分模板
三分整数模板
整数的三分可能具有不确定性,可以通过改变while循环的条件(while(l + 5 < r))来缩小范围,再通过
for(int i = l; i <= r; i++)
ans = min(ans, calc(i));
for(int i = 1; i <= r; i++)
ans = max(ans, calc(i));
//更新方式改成
l = lmid
r = rmid
来确定答案,下面的模板仅供参考,如果(WA)了,可以考虑通过这种方式改进。
凸函数的极大值
ll l, r;
while(l < r) {
ll lmid = l + (r - l) / 3;
ll rmid = r - (r - l) / 3;
if(calc(lmid) <= calc(rmid)) l = lmid + 1;
else r = rmid - 1;
}
printf("%lld
", max(calc(l), calc(r)));
凹函数的极小值
ll l, r;
while(l < r) {
ll lmid = l + (r - l) / 3;
ll rmid = r - (r - l) / 3;
if(calc(rmid) >= calc(lmid)) r = mid - 1;
else l = mid + 1;
}
printf("%lld
", min(calc(l), calc(r)));
三分小数模板
凸函数的极大值
double l, r;
for(int i = 0; i < 300; i++) {
double lmid = l + (r - l) / 3;
double rmid = r - (r - l) / 3;
if(calc(lmid) <= calc(rmid)) l = lmid;
else r = rmid;
}
printf("%.6f
", calc(l));
凹函数的极小值
double l, r;
for(int i = 0; i < 300; i++) {
double lmid = l + (r - l) / 3;
double rmid = r - (r - l) / 3;
if(calc(rmid) >= calc(lmid)) r = rmid;
else l = lmid;
}
printf("%.6f
", calc(l));