61# define COST(i,j) (cost[(i)*(n+1) + (j)])
62# define TREE(i,j) (tree[(i)*(n+1) + (j)])
68# define COST_OF(i,j) (cost.access((i)*(n+1) + (j)))
69# define ROOT_OF(i,j) (tree.access((i)*(n+1) + (j)))
93 for (
size_t i = 0; i < n; ++i)
97 auto sum_p = [&
prefix](
size_t i,
size_t j)
noexcept ->
double {
103 for (
size_t i = 1; i <= n + 1; ++i)
107 for (
size_t i = 1; i <= n; ++i)
109 TREE(i, i) =
static_cast<int>(i);
110 COST(i, i) = p[i - 1];
115 for (
size_t len = 2; len <= n; ++len)
117 for (
size_t i = 1; i + len - 1 <= n; ++i)
119 const size_t j = i + len - 1;
122 const size_t lo =
static_cast<size_t>(
ROOT_OF(i, j - 1));
123 const size_t hi =
static_cast<size_t>(
ROOT_OF(i + 1, j));
125 double min_cost = std::numeric_limits<double>::max();
126 size_t best_root = lo;
128 for (
size_t r = lo;
r <= hi; ++
r)
138 TREE(i, j) =
static_cast<int>(best_root);
139 COST(i, j) = min_cost + sum_p(i, j);
154template <
class Node,
typename Key>
157 const size_t i,
const size_t j)
160 return Node::NullPtr;
162 const int root_idx =
ROOT_OF(i, j);
164 LLINK(
root) = compute_tree<Node, Key>(
keys, tree, n, i, root_idx - 1);
165 RLINK(
root) = compute_tree<Node, Key>(
keys, tree, n, root_idx + 1, j);
198template <
class Node,
typename Key>
204 return compute_tree<Node, Key>(
keys, tree, n, 1, n);
WeightedDigraph::Node Node
__gmp_expr< T, __gmp_binary_expr< __gmp_expr< T, U >, unsigned long int, __gmp_root_function > > root(const __gmp_expr< T, U > &expr, unsigned long int l)
Node * build_optimal_tree(Key keys[], double p[], const size_t n)
Build an optimal binary search tree based on access probabilities.
Main namespace for Aleph-w library functions.
static Node * compute_tree(Key keys[], DynArray< int > &tree, const size_t n, const size_t i, const size_t j)
Recursively construct the optimal BST from the tree matrix.
static void prefix(Node *root, DynList< Node * > &acc)
static void compute_optimal_costs(DynArray< double > &cost, double p[], const size_t n, DynArray< int > &tree)
Compute optimal costs and tree structure using dynamic programming.
Lazy and scalable dynamic array implementation.