0% found this document useful (0 votes)
1 views3 pages

22BCE7873 ASG9

The document contains a Java program that calculates the cost of an Optimal Binary Search Tree (OBST). It includes methods for computing the optimal search tree cost and summing frequencies, along with a main method for user input and output. An example output demonstrates the program's functionality with sample keys and frequencies.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views3 pages

22BCE7873 ASG9

The document contains a Java program that calculates the cost of an Optimal Binary Search Tree (OBST). It includes methods for computing the optimal search tree cost and summing frequencies, along with a main method for user input and output. An example output demonstrates the program's functionality with sample keys and frequencies.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

1

NAME VEMURI PRAVEENA

REGISTRATION NUMBER 22BCE7873

ASSIGNMENT NUMBER 09

DATE 23-03-2025

>>WRITE JAVA PROGRAM TO DISPLAY COST OF OPTIMAL BINARY SEARCH


TREE(OBST)

CODE:
import java.util.Scanner;

public class OptimalBST {

public static int optimalSearchTree(int keys[], int freq[], int n) {


int cost[][] = new int[n + 1][n + 1];

for (int i = 0; i < n; i++) {


cost[i][i] = freq[i];
}

for (int L = 2; L <= n; L++) {


for (int i = 0; i <= n - L + 1; i++) {
int j = i + L - 1;
cost[i][j] = Integer.MAX_VALUE;

for (int r = i; r <= j; r++) {


int c = ((r > i) ? cost[i][r - 1] : 0) +
((r < j) ? cost[r + 1][j] : 0) +
sum(freq, i, j);
if (c < cost[i][j]) {
cost[i][j] = c;
}
}
}
}

return cost[0][n - 1];


}
2

public static int sum(int freq[], int i, int j) {


int s = 0;
for (int k = i; k <= j; k++) {
s += freq[k];
}
return s;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter the number of keys: ");


int n = scanner.nextInt();

int[] keys = new int[n];


int[] freq = new int[n];

System.out.println("Enter the keys:");


for (int i = 0; i < n; i++) {
keys[i] = scanner.nextInt();
}

System.out.println("Enter the frequencies of the keys:");


for (int i = 0; i < n; i++) {
freq[i] = scanner.nextInt();
}

int cost = optimalSearchTree(keys, freq, n);

System.out.println("Cost of Optimal Binary Search Tree is: " + cost);

scanner.close();
}
}

OUTPUT:
Enter the number of keys: 3
Enter the keys:
10 12 20
Enter the frequencies of the keys:
34 8 50
Cost of Optimal Binary Search Tree is: 142
...Program finished with exit code 0
3

Press ENTER to exit console.

—-------------------------------------------------THE END--------------------------------------------------------------

You might also like