39#include <gtest/gtest.h>
63 if (
root == Node::NullPtr)
66 EXPECT_EQ(
KEY(
root),
next) <<
"the key at the place " <<
next <<
" of the inorder";
68 cost += p[
static_cast<size_t>(
KEY(
root))] * depth;
76 const size_t n = p.
size();
78 auto at = [n, &cost] (
const size_t i,
const size_t j) ->
double & {
return cost(i * (n + 2) + j); };
79 for (
size_t len = 1; len <= n; ++len)
80 for (
size_t i = 1; i + len - 1 <= n; ++i)
82 const size_t j = i + len - 1;
84 for (
size_t k = i;
k <= j; ++
k)
86 double best = at(i, i - 1) + at(i + 1, j);
87 for (
size_t r = i + 1;
r <= j; ++
r)
88 best = std::min(best, at(i,
r - 1) + at(
r + 1, j));
89 at(i, j) = best +
sum;
91 return n == 0 ? 0 : at(1, n);
104 const size_t n = p.
size();
106 for (
size_t i = 0; i < n; ++i)
107 keys(i) =
static_cast<int>(i);
109 const std::unique_ptr<Node, Destroy_Tree> tree(
110 build_optimal_tree<Node, int>(n == 0 ?
nullptr : &
keys(0), n == 0 ? nullptr : &p(0), n));
112 const double cost = cost_of(tree.get(), p, 1,
next);
113 EXPECT_EQ(
next,
static_cast<int>(n)) <<
"the nodes of the tree, with " << n <<
" keys";
114 EXPECT_NEAR(cost, least_cost(p), 1e-9) <<
"with " << n <<
" keys";
118TEST(OptimalBinTree, WithoutKeysItIsEmpty)
121 EXPECT_EQ((build_optimal_tree<Node, int>(
nullptr,
nullptr, 0)), Node::NullPtr);
122 expect_an_optimal_tree(p);
126TEST(OptimalBinTree, ItsCostIsTheLeastOne)
128 std::mt19937
rng(20261125);
129 std::uniform_real_distribution<double> weight(0.0, 1.0);
130 for (
size_t n = 1; n <= 40; ++n)
131 for (
int trial = 0; trial < 5; ++trial)
134 for (
size_t i = 0; i < n; ++i)
136 expect_an_optimal_tree(p);
141TEST(OptimalBinTree, ItsCostIsTheLeastOneWithTiesAndZeros)
143 for (
size_t n = 1; n <= 33; ++n)
146 expect_an_optimal_tree(
equal);
149 expect_an_optimal_tree(zeros);
152 for (
size_t i = 0; i < n; i += 3)
154 expect_an_optimal_tree(some);
157 heavy(n - 1) = 1000.0;
158 expect_an_optimal_tree(heavy);
WeightedDigraph::Node Node
Simple dynamic array with automatic resizing and functional operations.
constexpr size_t size() const noexcept
Return the number of elements stored in the stack.
Node for binary search tree.
__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)
void destroyRec(Node *&root) noexcept
Free all the memory occupied by the tree root
Main namespace for Aleph-w library functions.
bool equal(Itor1 beg, const Itor1 &end, Itor2 cmpBeg, BinaryPredicate op=BinaryPredicate())
Test if two ranges are equal.
void next()
Advance all underlying iterators (bounds-checked).
T sum(const Container &container, const T &init=T{})
Compute sum of all elements.
Optimal Binary Search Tree construction using dynamic programming.
Dynamic array container with automatic resizing.
Utility functions for binary tree operations.
Basic binary tree node definitions.