最优二叉搜索树(java)

import java.util.Scanner;
public class SearchTree {
    public static void main(String[] args) {
        Scanner inp=new Scanner(System.in);
        int n=inp.nextInt();
        int b[]=new int[n+1];
        int a[]=new int[n+1];
        int s[][]=new int[n+2][n+1];
        int w[][]=new int[n+2][n+1];
        int m[][]=new int[n+2][n+1];
        for(int i=1;i<=n;i++)b[i]=inp.nextInt();
        for(int i=0;i<=n;i++)a[i]=inp.nextInt();
        T(n,b,a,s,w,m);
        P(1,n,s);
    }
    public static void T(int n,int b[],int a[],int s[][],int w[][],int m[][]){
        for(int i=0;i<=n;i++)w[i+1][i]=a[i];
        for(int r=1;r<=n;r++){
            for(int i=1;i<=n-r+1;i++){
                int j=i+r-1;
                s[i][j]=i;
                w[i][j]=w[i][j-1]+a[j]+b[j];
                m[i][j]=m[i][i-1]+w[i][j]+m[i+1][j];
                for(int k=i+1;k<=j;k++){
                    int t=m[i][k-1]+m[k+1][j]+w[i][j];
                    if(tpublic static void P(int i,int j,int s[][]){
        if(iint root=s[i][j];
            System.out.println("S"+root+"是根");
            if(s[i][root-1]>0)System.out.println("S"+root+"的左孩子是S"+s[i][root-1]);
            if(s[root+1][j]>0)System.out.println("S"+root+"的右孩子是S"+s[root+1][j]);
            P(i,root-1,s);
            P(root+1,j,s);
        }
    }
}

你可能感兴趣的:(算法)