最优二叉搜索树代码c++
时间: 2023-10-16 16:26:49 浏览: 77
以下是C++代码实现最优二叉搜索树问题:
```cpp
#include <bits/stdc++.h>
using namespace std;
const int INF = 0x3f3f3f3f;
const int MAXN = 1005;
int f[MAXN][MAXN], w[MAXN], sum[MAXN], n;
int main()
{
cin >> n;
for (int i = 1; i <= n; i++)
{
cin >> w[i];
sum[i] = sum[i - 1] + w[i];
}
memset(f, INF, sizeof(f));
for (int i = 1; i <= n; i++)
f[i][i] = w[i];
for (int len = 2; len <= n; len++)
for (int i = 1; i + len - 1 <= n; i++)
{
int j = i + len - 1;
for (int k = i; k <= j; k++)
{
int tmp = sum[j] - sum[i - 1];
if (k != i)
tmp += f[i][k - 1];
if (k != j)
tmp += f[k + 1][j];
f[i][j] = min(f[i][j], tmp);
}
}
cout << f[1][n] << endl;
return 0;
}
```
其中,数组 `w` 存储各个节点的权值,数组 `sum` 存储前缀和用于快速计算子树权值和,数组 `f` 存储最优解。算法时间复杂度为 $O(n^3)$,空间复杂度为 $O(n^2)$。
阅读全文