// 最优二叉查找树.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#define N 5// the number of real node
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
double p[N+1] = {0, 0.15, 0.1, 0.05, 0.1, 0.2}; // real node probility
double q[N+1] = {0.05, 0.1, 0.05, 0.05, 0.05, 0.1};// virtual node probility
double e[N+2][N+1],w[N+2][N+1];//e[i][j] for the shortest expectation, w[i][j] is the probility sum
int root[N+1][N+1] = {0};
for(int i=1;i<=N+1;i++)
{
e[i][i-1] = q[i-1];// only one virtual node
w[i][i-1] = q[i-1];
}
for(int m=1;m<=N;m++)
for(int i=1;i<=N+1-m;i++)
{
int j = i+m-1;
e[i][j] = 100;
w[i][j] = w[i][j-1] + q[j] + p[j];
for(int r=i;r<=j;r++)
{
double temp = e[i][r-1] + e[r+1][j] + w[i][j];//e[i][j]=p[r]+e[i][r-1]+w[i][r-1]+e[r+1][j]+w[r+1][j]
if(temp<e[i][j])
{
e[i][j] = temp;
root[i][j] = r;
}
}
}
for(int i=1;i<=N;i++)
{
for(int j=i;j<=N;j++)
cout<<root[i][j]<<" ";
cout<<endl;
}
cout<<"shortest expectation is "<<e[1][N]<<endl;
system("pause");
return 0;
}
动态规划之-最优二叉查找树
最新推荐文章于 2023-12-25 17:55:57 发布