C++编程完成动态规划法求解最优二叉搜索树,随机化查找数字及其查找成功概率,求出最优二叉搜索树。
时间: 2023-06-24 07:09:07 浏览: 143
以下是C++代码实现:
```
#include <iostream>
#include <vector>
#include <climits>
#include <ctime>
#include <cstdlib>
using namespace std;
double sum(vector<double> p, int i, int j) {
double s = 0;
for (int k = i; k <= j; k++) {
s += p[k];
}
return s;
}
void optimal_bst(vector<double> p, int n) {
vector<vector<double>> e(n + 1, vector<double>(n + 1, 0));
vector<vector<double>> w(n + 1, vector<double>(n + 1, 0));
vector<vector<int>> root(n + 1, vector<int>(n + 1, 0));
for (int i = 1; i <= n; i++) {
e[i][i - 1] = 0;
w[i][i - 1] = 0;
}
for (int len = 1; len <= n; len++) {
for (int i = 1; i <= n - len + 1; i++) {
int j = i + len - 1;
e[i][j] = INT_MAX;
w[i][j] = w[i][j - 1] + p[j];
for (int r = i; r <= j; r++) {
double t = e[i][r - 1] + e[r + 1][j] + w[i][j];
if (t < e[i][j]) {
e[i][j] = t;
root[i][j] = r;
}
}
}
}
cout << "最小代价为:" << e[1][n] << endl;
cout << "构造的最优二叉搜索树为:" << endl;
cout << "根节点为" << root[1][n] << endl;
vector<int> q;
q.push_back(root[1][n]);
vector<int> left(1, 1), right(1, n);
while (!q.empty()) {
int r = q.back();
q.pop_back();
int i = left.back();
left.pop_back();
int j = right.back();
right.pop_back();
if (r - 1 >= i && root[i][r - 1] != 0) {
cout << "根节点为" << root[i][r - 1] << "的左子树为" << i << "到" << r - 1 << endl;
left.push_back(i);
right.push_back(r - 1);
q.push_back(root[i][r - 1]);
}
if (r + 1 <= j && root[r + 1][j] != 0) {
cout << "根节点为" << root[r + 1][j] << "的右子树为" << r + 1 << "到" << j << endl;
left.push_back(r + 1);
right.push_back(j);
q.push_back(root[r + 1][j]);
}
}
}
int main() {
srand(time(nullptr));
vector<double> p{0, 0.15, 0.10, 0.05, 0.10, 0.20};
optimal_bst(p, 5);
cout << "随机化查找数字及其查找成功概率:" << endl;
double s = sum(p, 1, 5);
for (int i = 1; i <= 5; i++) {
double r = (double) rand() / RAND_MAX;
double sum = 0;
for (int j = 1; j <= 5; j++) {
sum += p[j];
if (r < sum / s) {
cout << "随机数为" << r << ",查找数字为" << j << ",查找成功概率为" << p[j] / s << endl;
break;
}
}
}
return 0;
}
```
其中,`optimal_bst`函数实现动态规划求解最优二叉搜索树,`sum`函数用于计算概率之和,`main`函数中实现随机化查找数字及其查找成功概率。在本例中,我们以一组数据{0.15,0.10,0.05,0.10,0.20}为例进行了求解。
阅读全文