算法设计与分析基础-8.3、最优二叉查找树

空间效率O(n2),时间效率O(n3)

当1<=i<=j<=n时,C[i,j]=min(i<=k<=j){C[i,k-1]+C[k+1,j]}+(pi+……+pj)

public class OptimalBST {
	private int nodeNum = 4;
	private int[][] R;
	private double[][] C;
	private double[] p;

	public OptimalBST(int nodeNum, double[] a) {
		super();
		this.nodeNum = nodeNum;
		p=new double[nodeNum];
		for (int i = 0; i < a.length; i++)
			this.p[i] = a[i];
		R = new int[nodeNum + 2][nodeNum + 1];
		C = new double[nodeNum + 2][nodeNum + 1];
	}

	public void optimalBST() {
		for (int i = 1; i <= nodeNum; i++) {
			C[i][i - 1] = 0;
			C[i][i] = p[i-1];
			R[i][i] = i;
		}
		C[nodeNum + 1][nodeNum] = 0;
		int d = 0, i = 0, j = 0, k = 0, kmin = 0;
		double minval = 0.0, sum = 0.0;
		for (d = 1; d <= nodeNum - 1; d++)
			// 对角线计数
			for (i = 1; i <= nodeNum - d; i++) {
				j = i + d;
				minval = 999;   //无穷大这里用999代替
				for (k = i; k <= j; k++) {
					if (C[i][k - 1] + C[k + 1][j] < minval) {
						minval = C[i][k - 1] + C[k + 1][j];
						kmin = k;
					}
				}
				R[i][j] = kmin;
				sum = p[i-1];
				for (int s = i; s < j; s++)
					sum += p[s];
				C[i][j] = minval + sum;
			}
	}
	public void showCR() {
		for (int i = 0; i < nodeNum+2; i++) {
			for (int j = 0; j < nodeNum+1; j++)
				System.out.print(C[i][j] + "  ");
			System.out.println();
		}
		for (int i = 0; i < nodeNum+2; i++) {
			for (int j = 0; j < nodeNum+1; j++)
				System.out.print(R[i][j] + "  ");
			System.out.println();
		}
	}
	public static void main(String[] argv) {
		double[] p = new double[] { 0.1, 0.2, 0.4, 0.3 };
		OptimalBST optimalBST=new OptimalBST(4, p);
		optimalBST.optimalBST();
		optimalBST.showCR();

	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值