三分查找

三分查找是二分查找的一個擴展,是基於分治思想的高效查找方法。

三分查找適用於凸函數或凹函數,它可以取得當前函數的最大值或最小值。

三分搜索實現主要是判斷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;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章