算法之动态规划最优二叉树
来源:互联网 发布:华为p9plus隐藏软件 编辑:程序博客网 时间:2024/05/05 07:17
- package com.eshore.sweetop.dynamicprogramming;
- public class BestBinTree {
-
-
-
-
- double[] p={0,0.04,0.06,0.08,0.02,0.10,0.12,0.14};
- double[] q={0.06,0.06,0.06,0.06,0.05,0.05,0.05,0.05};
- static int n=7;
-
- double[][] e=new double[n+2][n+1];
- double[][] w=new double[n+2][n+1];
- int[][] root=new int[n+2][n+2];
-
- public void optimalBest(){
- for (int i = 1; i < e.length; i++) {
- e[i][i-1]=q[i-1];
- w[i][i-1]=q[i-1];
- }
-
- for (int l = 1; l < n+1; l++) {
- for (int i = 1; i <= n-l+1; i++) {
- int j=i+l-1;
- e[i][j]=Double.MAX_VALUE;
- 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;
- System.out.println(r);
- root[i][j]=r;
- }
- }
- }
- }
- BestBinTree.display(root);
-
- BestBinTree.viewTree(root);
- }
-
- public static void display(double[][] a){
- for (int i = 1; i < a.length; i++) {
- for (int j = 1; j < a[0].length; j++) {
- System.out.print(String.format("%.2f", a[i][j])+"/t");
- }
- System.out.println();
- }
- }
-
- public static void display(int[][] a){
- for (int i = 1; i < a.length; i++) {
- for (int j = 1; j < a[0].length; j++) {
- if(i<=j)
- System.out.print(a[i][j]+" ");
- }
- System.out.println();
- }
- }
-
- public static void viewTree(int[][] a){
- System.out.println("根是k"+a[1][n]);
- view(a,a[1][n],1,n);
- }
-
- public static void view(int[][] a,int root,int i,int j){
- if(a[i][root-1]==0){
- System.out.println("k"+root+"左孩子是d"+(root-1));
- }else{
- System.out.println("k"+root+"左孩子是k"+a[i][root-1]);
- view(a,a[i][root-1],i,root-1);
- }
- if(a[root+1][j]==0){
- System.out.println("k"+root+"右孩子是d"+root);
- }else{
- System.out.println("k"+root+"右孩子是k"+a[root+1][j]);
- view(a,a[root+1][j],root+1,j);
- }
- }
-
-
- public static void main(String[] args) {
- BestBinTree bbt=new BestBinTree();
- bbt.optimalBest();
- }
-
- }