关闭

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

标签: cfloatimporttreestringclass
324人阅读 评论(0) 收藏 举报
分类:

 

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);
 }
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    多向别人学习