最优二叉搜索树问题

java实现:


public class 最优二叉搜索树问题 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		double p[] = {0,0.15,0.10,0.05,0.10,0.20};
		double q[] = {0.05,0.10,0.05,0.05,0.05,0.10};
		double p1[] = {0,0.04,0.06,0.08,0.02,0.10,0.12,0.14};
		double q1[] = {0.06,0.06,0.06,0.06,0.05,0.05,0.05,0.05};
		
		Optimal_BST(p, q, p.length-1);
		System.out.println();
		Optimal_BST(p1, q1, p1.length-1);
	}
	
	public static void Optimal_BST(double p[], double q[],int n) {
		double e[][] = new double[n+2][n+1];
		double w[][] = new double[n+2][n+1];
		int root[][] = new int[n+1][n+1];
		for(int i = 1; i<= n+1; i++) {
			e[i][i-1] = q[i-1];
			w[i][i-1] = q[i-1];
		}
		
		for(int l = 1; l <= n; l++) {
			for(int i = 1; i<= n-l+1; i++) {
				int j = i+l-1;
				e[i][j] = 1e9;
				w[i][j] = w[i][j-1] + p[j] + q[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;
					}
				}
			}
		}
		System.out.println(e[1][n]);
		construct_optimal_BST(root, 1, n);
	}
//	打印树根
	public static void construct_optimal_BST(int root[][], int i, int j) {
		if(i>j || root[i][j] == 0) {
			return ;
		}
		else {
			int r = root[i][j];
			System.out.print(r+" ");
			construct_optimal_BST(root, i, r-1);
			construct_optimal_BST(root, r+1, j);
		}
	}

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值