动态规划之-最优二叉查找树

// 最优二叉查找树.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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值