-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOBST.java
More file actions
66 lines (50 loc) · 1.94 KB
/
Copy pathOBST.java
File metadata and controls
66 lines (50 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import java.util.*;
class OBST {
public static void main(String[] args) {
System.out.println("Enter n, keys, p[i], and q[i] in order:");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();// no. of ids
int[] keys = new int[n];//sorted keys
for (int i = 0; i < n; i++) {
keys[i] = sc.nextInt();
}
double[] p = new double[n + 1];// prob of suceessful search
for (int i = 1; i <= n; i++) {
p[i] = sc.nextDouble();
}
double[] q = new double[n + 1];// prob of unsucessful search
for (int i = 0; i <= n; i++) {
q[i] = sc.nextDouble();
}
double minCost = optimalBST(p, q, n);
System.out.printf("%.4f\n", minCost);
sc.close();
}
public static double optimalBST(double[] p, double[] q, int n) {
double[][] e = new double[n + 2][n + 1]; // Expected cost
double[][] w = new double[n + 2][n + 1]; // Weight
int[][] root = new int[n + 1][n + 1]; // Root table
for (int i = 1; i <= n + 1; i++) { // single intervals
e[i][i - 1] = q[i - 1];
w[i][i - 1] = q[i - 1];
}
// values for chains of increasing length
for (int l = 1; l <= n; l++) {
for (int i = 1; i <= n - l + 1; i++) {
int j = i + l - 1;
e[i][j] = Double.MAX_VALUE;
w[i][j] = w[i][j - 1] + p[j] + q[j];
// each key k as root
for (int r = i; r <= j; r++) {
double t = e[i][r - 1] + e[r + 1][j] + w[i][j];
if (t < e[i][j]) {
e[i][j] = t;
root[i][j] = r;
}
}
}
}
// min expected cost stored in e[1][n]
return e[1][n];
}
}