我要一段最优二叉搜索树C++的代码
时间: 2024-05-03 21:17:59 浏览: 108
以下是一段最优二叉搜索树的C++代码:
```cpp
#include <iostream>
#include <climits>
using namespace std;
int sum(int freq[], int i, int j){
int s = 0;
for (int k = i; k <= j; k++){
s += freq[k];
}
return s;
}
int optimalSearchTree(int keys[], int freq[], int n){
int cost[n][n];
for (int i = 0; i < n; i++){
cost[i][i] = freq[i];
}
for (int L = 2; L <= n; L++){
for (int i = 0; i <= n-L+1; i++){
int j = i+L-1;
cost[i][j] = INT_MAX;
for (int r = i; r <= j; r++){
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 = sizeof(keys)/sizeof(keys[0]);
cout << "Cost of optimal BST is: " << optimalSearchTree(keys, freq, n) << endl;
return 0;
}
```
该代码使用动态规划的思想,构建了一个二维数组`cost`,其中`cost[i][j]`表示从第`i`个关键字到第`j`个关键字构成的最优二叉搜索树的代价。在计算`cost[i][j]`时,枚举根节点的位置`r`,计算左子树和右子树的代价以及根节点的代价之和,并选取最小的值作为`cost[i][j]`的值。最终,`cost[0][n-1]`即为整棵树的最小代价。
阅读全文