15.5 动态规划
15.5.1
1 #include <iostream> 2 #include <cstdio> 3 #include <cstdlib> 4 #include <string> 5 #include <vector> 6 #include <cassert> 7 #include <cmath> 8 #include <algorithm> 9 using namespace std; 10 11 #define MAX 111 12 #define MAXIUM 1111111 13 float e[MAX][MAX]; 14 float w[MAX][MAX]; 15 int root[MAX][MAX]; 16 17 void optimal_bst(float *p, float *q, int n) 18 { 19 for (int i = 1; i <= n + 1; i++) 20 { 21 e[i][i - 1] = q[i - 1]; 22 w[i][i - 1] = q[i - 1]; 23 } 24 for (int l = 1; l <= n; l++) 25 { 26 for (int i = 1; i <= n - l + 1; i++) 27 { 28 int j = i + l - 1; 29 e[i][j] = MAXIUM; 30 w[i][j] = w[i][j - 1] + p[j] + q[j]; 31 for (int r = i; r <= j; r++) 32 { 33 float t = e[i][r - 1] + e[r + 1][j] + w[i][j]; 34 if (t < e[i][j]) 35 { 36 e[i][j] = t; 37 root[i][j] = r; 38 } 39 } 40 } 41 } 42 } 43 44 void construct_optimal_bst(int i, int j, int up, int direction) 45 { 46 if (j < i) 47 { 48 printf("d%d is k%d's ", j, up); 49 if (direction == -1) 50 printf("left child\n"); 51 else if (direction == 1) 52 printf("right child\n"); 53 else 54 printf("root\n"); 55 return; 56 } 57 int r = root[i][j]; 58 if (up == -1) 59 printf("k%d is root\n", r); 60 else 61 { 62 printf("k%d is k%d's ", r, up); 63 if (direction == -1) 64 printf("left child\n"); 65 else if (direction == 1) 66 printf("right child\n"); 67 else 68 printf("root\n"); 69 } 70 construct_optimal_bst(i, r - 1, r, -1); 71 construct_optimal_bst(r + 1, j, r, 1); 72 } 73 74 int main(int argc, const char * argv[]) 75 { 76 float p[] = {0, 0.15, 0.10, 0.05, 0.10, 0.20}; 77 float q[] = {0.05, 0.10, 0.05, 0.05, 0.05, 0.10}; 78 optimal_bst(p, q, 5); 79 construct_optimal_bst(1, 5, -1, 0); 80 return 0; 81 }
15.5.2
利用上面的code,代价是3.12, 结构是
k5 is root k2 is k5's left child k1 is k2's left child d0 is k1's left child d1 is k1's right child k3 is k2's right child d2 is k3's left child k4 is k3's right child d3 is k4's left child d4 is k4's right child k7 is k5's right child k6 is k7's left child d5 is k6's left child d6 is k6's right child d7 is k7's right child
15.5.3
没有影响。
15.5.4
不会。