动态规划--最优二叉查找树(转载小妞滴。。。)

 

import java.util.Arrays;

public class BestTree {
	public int n;
	public double w[][];
	public double c[][];
	public  int r[][];

	public BestTree(int n)
	{
		 c=new double[n+2][n+1];
		 w=new double[n+2][n+1];r=new int[n+2][n+1];
	}
public void OptionBinarySearch(int n,double p[],double q[]){
  for(int i=1;i<=n;i++){
   c[i][i-1]=0;
   w[i][i-1]=q[i-1];
  }                                                                                                                                                                                                                                                                      public void OptionBinarySearch(int n,double p[],double q[]){
  for(int i=1;i<=n;i++){
   c[i][i-1]=0;
   w[i][i-1]=q[i-1];
  }  
for(int k=n;k>=1;k--){
   for(int i=1;i<=k;i++){
    int j=i-k+5;
    w[i][j]=w[i][j-1]+p[j]+q[j];
    //当i<=j时,c[i,j)=W(i,j)+min{c(i,k-1)+c(k+1,j)}
    c[i][j]=w[i][j]+c[i][i-1]+c[i+1][j];
    r[i][j]=i;
for(int m=i+1;m<=j;m++){
     double t=w[i][j]+c[i][m-1]+c[m+1][j];
     
     if((float)t<(float)c[i][j]){//通过比较,让c[i][j]的值最小
      c[i][j]=t;
      r[i][j]=m;
     }
    }
   }
  }
 }
public void BestSolution(int r[][],int i,int j){
  if(i<=j)
  {
  System.out.println("s"+i+"和s"+j+" 的根为:"+"s"+r[i][j]);
  BestSolution(r,i,r[i][j]-1);
  BestSolution(r,r[i][j]+1,j);
  }
 }
public static void main(String[] args){
  double p[]={0,0.15,0.1,0.05,0.1,0.2};
  double q[]={0.05,0.1,0.05,0.05,0.05,0.1};
  BestTree tree=new BestTree(5);
  tree.n=5;
  tree.OptionBinarySearch(5,p,q);
 
     for(int i=1;i<=5;i++){
      System.out.println(Arrays.toString(tree.r[i]));
     }
  tree.BestSolution(tree.r, 1, 5);
 }
}

    原文作者:满二叉树
    原文地址: https://blog.csdn.net/jiang_bing/article/details/7377694
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞