三分查找是二分查找的一个扩展,是基于分治思想的高效查找方法。
三分查找适用于凸函数或凹函数,它可以取得当前函数的最大值或最小值。
三分搜索实现主要是判断midl 和 midr 值的大小,
模板:
double solve(){ } double trisection_search(double left, double right){ double midl, midr; while(right - left > 1e-7){ midl = (left + right) / 2; midr = (midl + right) / 2; if(solve(midl) >= solve(midr)) right = midr; else left = midl; } }
例题:http://acm.hdu.edu.cn/showproblem.php?pid=3400
题解:该题很明显是一道三分搜索的题目,分别搜索ab直线段和bc直线段,同时进行判断,从而缩小范围,最后取得最小值。
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<string>
#include<cmath>
using namespace std;
const double esp = 1e-7;
struct Node{
double x, y;
}a, b, c, d, t1, t2;
double p, q, r;
double ab, cd;
double len(Node a1, Node a2){
double x = (a2.x - a1.x) * (a2.x - a1.x);
double y = (a2.y - a1.y) * (a2.y - a1.y);
double L = sqrt(x + y + esp);
return L;
}
double solve(double cdx){
t2.x = c.x + (d.x - c.x) * (cdx / cd);
t2.y = c.y + (d.y - c.y) * (cdx / cd);
return len(t1, t2) / r + (cd - cdx) / q;
}
double trisection_search2(double abx){
t1.x = a.x + (b.x - a.x) * (abx / ab);
t1.y = a.y + (b.y - a.y) * (abx / ab);
double left = 0, right = cd;
double midl, midr;
double ans, tmp1, tmp2;
while(right - left > 1e-7){
midl = (left + right) / 2;
midr = (midl + right) / 2;
if((tmp1 = solve(midl)) <= (tmp2 = solve(midr)))
right = midr;
else left = midl;
ans = min(tmp1, tmp2);
}
return ans + abx / p;
}
double trisection_search1(double left, double right){
double midl, midr;
double ans, tmp1, tmp2;
while(right - left > 1e-7){
midl = (left + right) / 2;
midr = (midl + right) / 2;
if((tmp1 = trisection_search2(midl)) <= (tmp2 = trisection_search2(midr)))
right = midr;
else left = midl;
ans = min(tmp1, tmp2);
}
return ans;
}
int main()
{
int T;
scanf("%d", &T);
while(T--){
scanf("%lf%lf%lf%lf", &a.x, &a.y, &b.x, &b.y);
scanf("%lf%lf%lf%lf", &c.x, &c.y, &d.x, &d.y);
scanf("%lf%lf%lf", &p, &q, &r);
ab = len(a, b);
cd = len(c, d);
double ans = trisection_search1(0, ab);
printf("%.2lf\n", ans);
}
return 0;
}