数据结构中的最优二叉搜索树
给定一组已排序的整数和一个表示频率的数组 freq。我们的任务是用这些数据创建一个二叉搜索树,以查找所有搜索的最小开销。
创建了一个辅助数组 cost[n, n] 来求解和存储子问题的解答。开销矩阵将包含数据,以自下而上的方式解决问题。
输入 − 关键字作为节点及频率。
Keys = {10, 12, 20} Frequency = {34, 8, 50}
输出 − 最小开销是 142。
以下是给定值可能出现的二叉搜索树。
对于情况 1,开销为:(34*1) + (8*2) + (50*3) = 200
对于情况 2,开销为:(8*1) + (34*2) + (50*2) = 176。
类似地,对于情况 5,开销为:(50*1) + (34 * 2) + (8 * 3) = 142(最小)
算法
optCostBst(keys, freq, n) Input: Keys to insert in BST, frequency for each keys, number of keys. Output: Minimum cost to make optimal BST. Begin define cost matrix of size n x n for i in range 0 to n-1, do cost[i, i] := freq[i] done for length in range 2 to n, do for i in range 0 to (n-length+1), do j := i + length – 1 cost[i, j] := ∞ for r in range i to j, done if r > i, then c := cost[i, r-1] else c := 0 if r < j, then c := c + cost[r+1, j] c := c + sum of frequency from i to j if c < cost[i, j], then cost[i, j] := c done done done return cost[0, n-1] End
示例
#include <iostream> using namespace std; int sum(int freq[], int low, int high){ //sum of frequency from low to high range int sum = 0; for (int k = low; k <=high; k++) sum += freq[k]; return sum; } int minCostBST(int keys[], int freq[], int n){ int cost[n][n]; for (int i = 0; i < n; i++) //when only one key, move along diagonal elements cost[i][i] = freq[i]; for (int length=2; length<=n; length++){ for (int i=0; i<=n-length+1; i++){ //from 0th row to n-length+1 row as i int j = i+length-1; cost[i][j] = INT_MAX; //initially store to infinity for (int r=i; r<=j; r++){ //find cost when r is root of subtree int c = ((r > i)?cost[i][r-1]:0)+((r < j)?cost[r+1][j]:0)+sum(freq, i, j); if (c < cost[i][j]) cost[i][j] = c; } } } return cost[0][n-1]; } int main(){ int keys[] = {10, 12, 20}; int freq[] = {34, 8, 50}; int n = 3; cout << "Cost of Optimal BST is: "<< minCostBST(keys, freq, n); }
输出
Cost of Optimal BST is: 142
广告