【发布时间】:2015-05-14 15:22:54
【问题描述】:
我正在解决一个问题,该问题通过尽可能最好的方式来计算二叉搜索树所需的最小遍历次数。我确实在网上遇到了一个解决方案,我已经理解了,但是我手动对样本输入进行了一些计算,并没有得到正确的结果。
下面是代码
#include <stdio.h>
#include <limits.h>
// A utility function to get sum of array elements freq[i] to freq[j]
int sum(int freq[], int i, int j);
/* A Dynamic Programming based function that calculates minimum cost of
a Binary Search Tree. */
int optimalSearchTree(int keys[], int freq[], int n)
{
/* Create an auxiliary 2D matrix to store results of subproblems */
int cost[n][n];
/* 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 a single key, cost is equal to frequency of the key
for (int i = 0; i < n; i++)
cost[i][i] = freq[i];
// Now we need to consider chains of length 2, 3, ... .
// L is chain length.
for (int L=2; L<=n; L++)
{
// i is row number in cost[][]
for (int i=0; i<=n-L+1; i++)
{
// Get column number j from row number i and chain length L
int j = i+L-1;
cost[i][j] = INT_MAX;
// Try making all keys in interval keys[i..j] as root
for (int r=i; r<=j; r++)
{
// c = cost when keys[r] becomes root of this 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];
}
// A utility function to get sum of array elements freq[i] to freq[j]
int sum(int freq[], int i, int j)
{
int s = 0;
for (int k = i; k <=j; k++)
s += freq[k];
return s;
}
// Driver program to test above functions
int main()
{
int keys[] = {10, 12, 20};
int freq[] = {34, 8, 50};
int n = sizeof(keys)/sizeof(keys[0]);
printf("Cost of Optimal BST is %d ", optimalSearchTree(keys, freq, n));
return 0;
}
例如对于输入 整数键[] = {1,2,3}; 整数频率[] = {10,3,1};
我应该得到 18,但我得到 19
对于这个输入 整数键[] = {1,2,3,4}; 整数频率[] = {5,4,1,200};
我应该得到 225 我得到 226
对于这个输入 整数键[] = {1,2,3,4,5,6}; 整数频率[] = {33,1,409,2,1,34};
我应该得到 997,但我得到 556
对于这个输入 整数键[] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20}; 整数频率[] = {5,5,5,5,5,5,5,5,5,5,167,5,5,5,5,5,5,5,5,5};
我应该得到 789,但我得到 532
怎么了?
【问题讨论】:
-
您能否解释一下
keys和freq这些值代表什么以及您尝试应用的算法? -
@chmike 这是一个很好的来源webcache.googleusercontent.com/…
-
当您使用调试器并单步执行代码时,哪些行存在问题?
-
案例:int keys[] = {1,2,3};整数频率 [] = {10,3,1};结果应该是 19
-
假设您有三个词,A、B 和 C。您搜索 A 10 次、B 3 次和 C 1 次。您可以将它们排列为 A 在左分支上,B 和 C 在右分支上成对排列。就处理所有搜索必须遍历的边数而言,一条边需要 10 次遍历才能到达 A,然后要遍历 4 次边才能到达 B 和 C 对,然后向下 3 次边到 B,沿着边向下 1 到 C。这棵树的边遍历总数为 10 + 4 + 3 + 1,即 18。
标签: c algorithm dynamic-programming