DP24 最优BST Optimal Binary Search Tree @geeksforgeeks

最优二叉搜索树(Optimal BST)-算法导论 问题描述: 维基百科定义: https://en.wikipedia.org/wiki/Optimal_binary_search_tree  In the static optimality problem as defined by Knuth we are given a set of n{\displaystyle n} ordered elements and a set of 2 阅读详情

Given a sorted array keys[0.. n-1] of search keys and an array freq[0.. n-1] of frequency counts, wherefreq[i] is the number of searches to keys[i]. Construct a binary search tree of all keys such that the total cost of all the searches is as small as possible.

Let us first define the cost of a BST. The cost of a BST node is level of that node multiplied by its frequency. Level of root is 1.

Example 1
Input:  keys[] = {10, 12}, freq[] = {34, 50}
There can be following two possible BSTs 
        10                       12
          \                     / 
           12                 10
          I                     II
Frequency of searches of 10 and 12 are 34 and 50 respectively.
The cost of tree I is 34*1 + 50*2 = 134
The cost of tree II is 50*1 + 34*2 = 118 

Example 2
Input:  keys[] = {10, 12, 20}, freq[] = {34, 8, 50}
There can be following possible BSTs
    10                12                 20         10              20
      \             /    \              /             \            /
      12          10     20           12               20         10  
        \                            /                 /           \
         20                        10                12             12  
     I               II             III             IV             V
Among all possible BSTs, cost of the fifth BST is minimum.  
Cost of the fifth BST is 1*50 + 2*34 + 3*8 = 142

1) Optimal Substructure:
The optimal cost for freq[i..j] can be recursively calculated using following formula.
optCost(i, j) = \sum\limits_{k=i}^j freq[k] + \min\limits_{r=i}^j  [ optCost(i, r-1) + optCost(r+1, j) ]

We need to calculate optCost(0, n-1) to find the result.

The idea of above formula is simple, we one by one try all nodes as root (r varies from i to j in second term). When we make rth node as root, we recursively calculate optimal cost from i to r-1 and r+1 to j.
We add sum of frequencies from i to j (see first term in the above formula), this is added because every search will go through root and one comparison will be done for every search.

2) Overlapping Subproblems
Following is recursive implementation that simply follows the recursive structure mentioned above.


Dynamic Programming Solution
Following is C/C++ implementation for optimal BST problem using Dynamic Programming. We use an auxiliary array cost[n][n] to store the solutions of subproblems. cost[0][n-1] will hold the final result. The challenge in implementation is, all diagonal values must be filled first, then the values which lie on the line just above the diagonal. In other words, we must first fill all cost[i][i] values, then all cost[i][i+1] values, then all cost[i][i+2] values. So how to fill the 2D array in such manner> The idea used in the implementation is same as Matrix Chain Multiplication problem, we use a variable ‘L’ for chain length and increment ‘L’, one by one. We calculate column number ‘j’ using the values of ‘i’ and ‘L’.


package DP;

public class OptimalBinarySearchTree {

	public static void main(String[] args) {
		int[] keys = {10,12,20};
		int[] freq = {34,8,50};
		int n = keys.length;
		System.out.println("Cost of Optimal BST is " + optimalSearchTreeRec(keys, freq, n));
		System.out.println("Cost of Optimal BST is " + optimalSearchTreeDP(keys, freq, n));
	}
	
	public static int optCost(int[] freq, int begin, int end){
		if(end < begin){		// If there are no elements in this subarray
			return 0;
		}
		if(begin == end){		// If there is one element in this subarray
			return freq[begin];
		}
		
		// 每往下走一步,都要加上从begin到end的freq和
		int fsum = sum(freq, begin, end);	// Get sum of freq[i], freq[i+1], ... freq[j]
		int min = Integer.MAX_VALUE;		// Initialize minimum value
		
		// One by one consider all elements as root and recursively find cost
		// of the BST, compare the cost with min and update min if needed
		for(int r=begin; r<=end; r++){
			int cost = optCost(freq, begin, r-1) + optCost(freq, r+1, end);
			min = Math.min(min, cost);
		}
		
		return min + fsum;		// Return minimum value
	}
	
	// A utility function to get sum of array elements freq[i] to freq[j]
	public static int sum(int[] freq, int begin, int end){
		int sum = 0;
		for(int i=begin; i<=end; i++){
			sum += freq[i];
		}
		return sum;
	}
	
	// The main function that calculates minimum cost of a Binary Search Tree.
	// It mainly uses optCost() to find the optimal cost.
	public static int optimalSearchTreeRec(int[] keys, int[] freq, int n){
		// Here array keys[] is assumed to be sorted in increasing order.
	     // If keys[] is not sorted, then add code to sort keys, and rearrange
	     // freq[] accordingly.
		return optCost(freq, 0, n-1);
	}

	/* A Dynamic Programming based function that calculates minimum cost of
	   a Binary Search Tree. */
	public static int optimalSearchTreeDP(int[] keys, int[] freq, int n){
		int[][] cost = new int[n][n];		 /* Create an auxiliary 2D matrix to store results of subproblems */
		
		/* cost[i][j] = Optimal cost of binary search tree that can be
	       formed from keys[i] to keys[j].
	       cost[0][n-1] will store the resultant cost */
		for(int i=0; i<n; i++){
			cost[i][i] = freq[i];	// 只有一个元素时,cost为freq,就是把那个元素作为root
		}
		
		// Now we need to consider chains of length 2, 3, ... .
		for(int L=2; L<=n; L++){		// L is chain length.
			for(int begin=0; begin<n-L+1; begin++){		// begin: begin index in keys
				int end = begin+L-1;		// end: end index in keys
				cost[begin][end] = Integer.MAX_VALUE;
				
				// Try making all keys in interval keys[begin..end] as root
				for(int r=begin; r<=end; r++){
					// c = cost when keys[r] becomes root of this subtree
					int c = (r>begin ? cost[begin][r-1] : 0) + (r<end ? cost[r+1][end] : 0) + sum(freq, begin, end);
					cost[begin][end] = Math.min(cost[begin][end], c);
				}
			}
		}
		
		return cost[0][n-1];
	}
	
	
}



http://www.geeksforgeeks.org/dynamic-programming-set-24-optimal-binary-search-tree/

UVA10304-Optimal Binary Search Tree(最优二分检索树) Optimal Binary Search TreeGiven a set S = (e1, e2, …, en) of n distinct elements such that e1 < e2 < … < en and considering a binary search tree (see the previous problem) of the elements of S, it is 阅读详情

相关推荐

Optimal Binary Search Tree

关于最优二叉查找树的开山之作,介绍了最优二叉查找树的概念,以及构造最优二叉查找树的动态规划算法,来自D. E. KNUTH,发表于1971年,亦可从这里下载:http://www.springerlink.com/content/uj8j384065436q61/fulltext.pdf

算法与数据结构学习笔记-最优二叉搜索树(optimal binary search tree)的动态规划实现详解

一串字符中可能进行多次查找,每个字符被查找到的频率都不同,如何根据字符被查找到的频率,建立一个二叉搜索树,使得花费时间最少呢? 题目:给定一列按升序排列的键值K=[k1,k2,...,kn]K=[k_1,k_2,...,k_n]K=[k1​,k2​,...,kn​]和它们被搜索到的频率P=[p1,p2,...,pn]P=[p_1,p_2,...,p_n]P=[p1​,p2​,...,pn​],建立...

mschessy的博客 4246

optimal binary search tree

最小成本二分检索树optimal binary optimal binary

最优二叉搜索树(Optimal Binary Search Tree)_20230401

最优二叉搜索树, 动态规划,C语言

Jasonchen1224的博客 3494

PotPlayer终极画质调校:深入MadVR渲染器设置,让你的显示器发挥100%潜力

本文深入探讨了如何通过MadVR渲染器优化PotPlayer的画质设置,充分发挥高端显卡和显示器的潜力。从色彩空间匹配、色深优化到HDR元数据处理,提供了一套完整的配置指南,帮助用户实现影院级视觉体验。特别适合拥有NVIDIA RTX或AMD RX系列显卡的用户进行精细调校。

weixin_42530458的博客 599

ESP32-CAM入门教程

ArduinoESP32-CAM下载模块(接上USB就能用,很方便,如果没有买就只有资金用USB-TTL了)如下图两个合在一起如下图。

qq_48778364的博客 3万+

[题集]Lecture 8. Dynamic Programming

1.To solve a problem by dynamic programming instead of recursions, the key approach is to store the results of computations for the subproblems so that we only have to compute each different subproblem once. Those solutions can be stored in an array or a h

HGGshiwo的博客 1257

Zynq裸机调试RTL8211FS网卡踩坑记:从ping不通到完美兼容的完整代码修改

本文详细记录了在Zynq平台上使用Xilinx SDK(XSDK)调试RTL8211FS网卡的完整过程,从最初的ping不通问题到最终实现完美兼容的解决方案。通过分析PHY芯片的寄存器配置差异,提供了关键代码修改和调试技巧,帮助开发者快速解决类似问题。

weixin_42550597的博客 419

uva 10304 - Optimal Binary Search Tree(区间dp)

题意: 建一棵树,左子树小于根小于右子数,现要求求出f1*h1+f2*h2+...的最小(f是权值,h是高度) 那么用区间dp,枚举i到j以k为根的最小总数 那么每增加一层(除了根),就会增加sum:i->j并且减去a[k]; #include #include #include #include using namespace std; const int maxn = 26

deepquiet的博客 335

Multisim实战:从零搭建体温检测报警电路(附完整仿真文件+调试技巧)

本文详细介绍了如何使用Multisim从零搭建体温检测报警电路,涵盖LM35温度传感器、LM358运算放大器等核心器件的选型与连接,以及信号调理、阈值比较和数码管显示等关键电路设计。附赠完整仿真文件和实用调试技巧,帮助电子工程初学者快速掌握体温温度检测系统的设计与实现。

weixin_28285943的博客 292

银行监管报送系统介绍(十五):金融审计平台

金审平台主要包括基础、财务、结算、信贷和中间业务五大板块,主要服务于审计署对中国银行的各项审计任务,同时也可为行内审计、稽核检查、数据分析、总分行提供基础数据服务,为实现基础数据共享提供了有力的数据保障。2019年1月某全国性股份制商业银行收到审计署2019-23号文,文中指出为进一步提高审计数据质量,审计署审计组派员前往9家重点商业银行,就完善标准化数据的相关情况与各银行有关部门进行讨论协商。关于数据报送频率及报送内容:数据从2019年4月开始,按月报送,即于每月25日之前报送上月数据;

银行信息系统应用架构详解 2053

算法导论实践——OptimalBST(最优搜索二叉树)

算法导论实践——OptimalBST(最优搜索二叉树)——这波是脑壳痛理论C#实践OptimalBinarySearchTree.csProgram.cs 动态规划的思想,很巧妙(话又说回来,什么东西不巧妙呢) 理论 思路就是,取得Kr∈{Ki...Kj},以Kr为根节点构造两颗最优BST, {Ki...Kr-1}和{Kr+1...Kj} 1.设E[i,j]代表{Ki...Kj}和{Di-1....

不定期更新系统使用、编程小技巧,哔哩哔哩账号:https://space.bilibili.com/399455629,欢迎关注 1266

玩转Docker小游戏项目系列: Docker部署红心纸牌网页小游戏

玩转Docker小游戏项目系列: Docker部署红心纸牌网页小游戏

jks212454的博客 420

最优二叉查找树—动态规划C++

最优二叉查找树欢迎使用Markdown编辑器新的改变功能快捷键合理的创建标题,有助于目录的生成如何改变文本的样式插入链接与图片如何插入一段漂亮的代码片生成一个适合你的列表创建一个表格设定内容居中、居左、居右SmartyPants创建一个自定义列表如何创建一个注脚注释也是必不可少的KaTeX数学公式新的甘特图功能,丰富你的文章UML 图表FLowchart流程图导出与导入导出导入 欢迎使用Markdown编辑器 你好! 这是你第一次使用 Markdown编辑器 所展示的欢迎页。如果你想学习如何使用Markdo

qq_45644525的博客 1万+

PCB层叠结构与阻抗计算

1.Core 和 PP PCB两个重要组成部分:Core 和 Prepreg(半固态片,简称PP)。 如下图所示, Core 的两个表面都铺有铜箔,可作为信号层、电源层、地层等导电层,Core的上下表面之间填充的是固态材料; PP的表面不铺铜,在PCB中起填充作用,其材质是半固体的树脂材料,因此比Core略软一些。 在制作多层板时,需配合使用Core和PP,一般在两个Core 之间应选PP作为填...

sinat_15677011的博客 1万+

RAGFlow 系列教程 第14课:GraphRAG -- 知识图谱增强检索

RAGFlow v0.25.0深度解读了GraphRAG技术,通过构建知识图谱解决传统RAG在多跳推理问题上的局限。系统支持General GraphRAG和Light GraphRAG两种实现,包含四阶段构建流程:实体关系抽取、实体消解、社区检测和图持久化。核心代码位于rag/graphrag目录,采用LLM驱动的抽取机制,结合编辑距离和LLM确认的实体消解策略,以及Leiden社区检测算法。KGSearch模块通过多信号融合检索(实体+关系+N-hop+社区)实现高效查询。该系统将非结构化文本转化为可推

weixin_43674738的博客 101

《算法导论》之最优二叉搜索树

最优二叉搜索树 假定我们正在设计一个程序,实现英语文本到法语的翻译。对英语文本中出现的每个单词,我们需要查找对应的法语单词。为了实现这些查找操作,可以创建一棵二叉搜索树,将n个英语单词作为关键字,对应的法语单词作为关联数据。由于文本中的每个单词都要进行搜索,我们希望花费在搜索上的总时间尽量少。 通过红黑树或其他平衡搜索树结构,我们可以假定每次搜索时间为O(lgn) 。但由于单词出现的频率是不同的,...

sunshine_lyn的博客 1万+

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

Geeks 面试题 : Optimal Binary Search Tree

Dynamic Programming | Set 24 (Optimal Binary Search Tree) Given a sorted arraykeys[0.. n-1]of search keys and an arrayfreq[0.. n-1]of frequency counts, wherefreq[i]is the number of sear...

编程语言小筑 266

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

UVA | Optimal Binary Search Tree

原题题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=514&page=show_problem&problem=1245Given a set S = (e1, e2, …, en) of n distinct elements such that e1 < e2 < … < en

益达的小作坊 1211

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

UVa:10304 Optimal Binary Search Tree(动态规划)

经典的OBST问题。 我用了O(n^3)的解法,dp【i】【j】=min{dp【i】【k-1】+dp【k+1】【j】+sum【i】-sum【j-1】+val【k】}其中i 一开始想了一个O(n^4)的算法,用dp【i】【j】【d】表示区间【i,j】段数字深度为d时候的最小值,这样多加了一维把问题给复杂化了。 实际上这个题可以用四边形不等式优化成O(n^2),以后贴上代码。 O(n^3):

Fighting 950

uva10304 Optimal Binary Search Tree

区间dp

YHaX的博客 438

uva10304 Optimal Binary Search Tree(最优二叉排序树 区间dp)

题意:给n个符号建立一棵排序二叉树,给出每个符号检索的频率,要求从检索的次数最小。 分析:《训练指南》P64,很详细。 代码: #include<bits/stdc++.h> using namespace std; const int INF = 0x3f3f3f3f; const int N = 210; int n; int w[N]; int sum[N]; int f[...

常胜将军的博客 611

UVA10304- Optimal Binary Search Tree(最优排序二叉树OBST)

题意:给n的数字建立一棵排序二叉树,要求

懒人一枚。 1691

算法java实现--动态规划--最优二叉树搜索

最优erchasoushuo算法的java实现(动态规划法) 具体问题描述以及C/C++实现参见网址 http://blog.youkuaiyun.com/liufeng_king/article/details/8683136

qipanliming的专栏 6344
上一篇: DP23 Bellman–Ford Algorithm @geeksforgeeks
下一篇: DP25 子集和问题 Subset Sum Problem @geeksforgeeks
chiiis
博客等级 码龄14年 422粉丝 429原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值