您的位置:首页 > 其它

算法之动态规划最优二叉树

2008-10-27 19:27 330 查看
package com.eshore.sweetop.dynamicprogramming;

public class BestBinTree {
    //关键字节点,p[0]为构造数据
//  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};
    //规模
//  int n=5;
    
    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(w);
//      BestBinTree.display(e); 
        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]
);
        view(a,a[1]
,1,n);
//      System.out.println(a[6][7]);
    }
    
    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();
    }
    
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: