/** * @file OptRoot.java * @synopsis A simple program to compute the optimal Binary Search tree. * THIS IS OBTAINED BY MODIFICATION OF Opt.java. * The structure of the optimal tree is also computed. * Input is an array p of frequencies. * Optional input: array of keys * CONVENTION: * the first index (i=0) of vectors and arrays are not used. * * @author Chee Yap * @date Apr 23, 2001 (for Basic Algorithms class) */ public class OptRoot { // Members: int n; // number of keys double[] p; // this is the probabality or frequency vector // NOTE: indexing is from 1 (not 0) to n String[] keys; // This is optional (will be null if not used) double[][] cost; // This is A(i,j) in lectures and text double[][] prob; // This is P(i,j) in lectures int[][] root; // To keep track of the root // Constructors: OptRoot(double[] q, String[] k) { n = q.length - 1; p = q; keys = k; cost = new double[n+1][n+1]; prob = new double[n+1][n+1]; root = new int[n+1][n+1]; best(); // calls the main subroutine } //OptRoot(q, k) // Methods: /****************************************************** THIS IS THE MAIN ROUTINE ******************************************************/ void best() { // init: for (int i = 1; i <= n; i++) { cost[i][i-1] = 0; cost[i-1][i] = 0; cost[i][i] = p[i]; prob[i][i] = p[i]; root[i][i] = i; cost[i][i-1] = 0; } // loop: for (int k = 2; k <= n; k++) { for (int i = 1; i <= n-k+1; i++) { double val = cost[i][i+k-2]; int rr = i+k-1; for (int r = i; r < i+k-1; r++) if (val > cost[i][r-1] + cost[r+1][i+k-1]) { rr = r; val = cost[i][r-1] + cost[r+1][i+k-1]; } root[i][i+k-1] = rr; prob[i][i+k-1] = p[i+k-1] + prob[i][i+k-2]; cost[i][i+k-1] = prob[i][i+k-1] + val; } // for i } // for k } // best() /****************************************************** prints all subproblems EXERCISE: modify this to only print the optimal tree ******************************************************/ void output() { for (int k = 1; k <= n; k++) { System.out.println("Size k = " + k); for (int i = 1; i <= n-k+1; i++) { int j = i+k-1; System.out.print("Subproblem (i,j) = (" + i + ", " + j + "): cost = " + cost[i][j] + ", root = " + root[i][j]); if (keys != null) System.out.println(", key = " + keys[root[i][j]]); else System.out.println(); } } } // output() /****************************************************** Main method ******************************************************/ public static void main( String[] args) { // sample input with 6 keys // (the first is a dummy key) String[] keys = { "dummy", "a", "and", "he", "of", "the", "to"}; double[] p = { 0, 0.2, 0.24, 0.16, 0.28, 0.04, 0.08}; // construct the optimal tree: OptRoot S = new OptRoot(p, keys); // print the optimal tree; System.out.println( "**************************************************\n" + " ALL SUBPROBLEMS\n" + "**************************************************"); S.output(); } // main }//class OptRoot