/** * @file Opt.java * @synopsis A simple program to compute the optimal Binary Search tree * in which you are given an input vector p of frequencies. * 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 Opt { // Members: int n; // number of keys int[] p; // this is the probabality or frequency vector // NOTE: indexing is from 1 (not 0) to n int[][] cost; // This is A(i,j) in lectures and text int[][] prob; // This is P(i,j) in lectures // Constructors: Opt(int[] q) { n = q.length - 1; p = q; cost = new int[n+1][n+1]; prob = new int[n+1][n+1]; best(); // calls the main subroutine } //Opt(q, k) // Methods: /****************************************************** THIS IS THE MAIN ROUTINE ******************************************************/ void best() { // init: for (int i = 1; i <= n; i++) { cost[i][i] = p[i]; prob[i][i] = p[i]; cost[i][i-1] = 0; } // loop: for (int k = 2; k <= n; k++) { for (int i = 1; i <= n-k+1; i++) { // initial guess at optimal root is rr = i+k-1: prob[i][i+k-1] = p[i+k-1] + prob[i][i+k-2]; int val = cost[i][i+k-2]; for (int r = i; r < i+k-1; r++) if (val > cost[i][r-1] + cost[r+1][i+k-1]) { val = cost[i][r-1] + cost[r+1][i+k-1]; } cost[i][i+k-1] = prob[i][i+k-1] + val; } // for i } // for k } // best() /****************************************************** prints all subproblems EXERCISE: modify this to 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.println("Subproblem (i,j) = (" + i + ", " + j + "): cost = " + cost[i][j]); } } } // 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"}; int[] p = { 0, 13, 16, 12, 11, 40, 12}; // construct the opitmal tree: Opt S = new Opt(p); // print the optimal tree; System.out.println( "**************************************************\n" + " ALL SUBPROBLEMS\n" + "**************************************************"); S.output(); } // main }//class Opt