三分查找

三分查找是二分查找的一个扩展,是基于分治思想的高效查找方法。

三分查找适用于凸函数或凹函数,它可以取得当前函数的最大值或最小值。

三分搜索实现主要是判断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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值