#include "stdafx.h" #include <iostream> #include <math.h> using namespace std; #define INFINITY 100000000 double e[7][6],w[7][6];//5个关键字 i从1--6 j从0--5 int root[6][6];//r表示ki。。kj序列的根 void Optimal_BST (const double *p, const double *q,int n) { for (int i=1; i<=n+1; i++) { e[i][i-1] = q[i-1]; w[i][i-1] = q[i-1]; } for (int l=1; l<=n; l++) { for (int i=1; i<=n-l+1; i++) { int j = i+l-1; e[i][j] = INFINITY; w[i][j] = w[i][j-1] + p[j] + q[j]; 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; } } } } return; } int main() { double p[] = {0.0,0.15,0.10,0.05,0.10,0.20}; double q[] = {0.05,0.10,0.05,0.05,0.05,0.10}; Optimal_BST (p, q, 5); for (int i = 1; i <= 6; i++) { for (int j = i - 1; j <=5 ; j++) { if(j != 0) cout<<" "; cout<<e[i][j]; } cout<<endl; } return 0; }