#include <algorithm>
#include <cassert>
#include <functional>
#include <iostream>
#include <memory>
#include <queue>
#include <stdexcept>
#include <vector>
struct Tree {
  int value;
  std::unique_ptr<Tree> left, right;
  explicit Tree(int x) : value(x) {}
};
// 前序、中序值互异且表示同一棵树；位置查找使用线性搜索，最坏 O(n^2)。
std::unique_ptr<Tree> build(const std::vector<int> &pre,
                            const std::vector<int> &in, std::size_t &pos, int l,
                            int r) {
  if (l == r)
    return {};
  if (pos >= pre.size())
    throw std::invalid_argument("bad traversals");
  int value = pre[pos++];
  auto it = std::find(in.begin() + l, in.begin() + r, value);
  if (it == in.begin() + r)
    throw std::invalid_argument("bad root");
  int k = static_cast<int>(it - in.begin());
  auto t = std::make_unique<Tree>(value);
  t->left = build(pre, in, pos, l, k);
  t->right = build(pre, in, pos, k + 1, r);
  return t;
}
int height(const Tree *t) {
  return t ? 1 + std::max(height(t->left.get()), height(t->right.get())) : 0;
}
void postorder(const Tree *t, std::vector<int> &out) {
  if (!t)
    return;
  postorder(t->left.get(), out);
  postorder(t->right.get(), out);
  out.push_back(t->value);
}
std::vector<int> level(const Tree *t) {
  std::vector<int> out;
  if (!t)
    return out;
  std::queue<const Tree *> q;
  q.push(t);
  while (!q.empty()) {
    auto p = q.front();
    q.pop();
    out.push_back(p->value);
    if (p->left)
      q.push(p->left.get());
    if (p->right)
      q.push(p->right.get());
  }
  return out;
}
long long huffmanCost(std::vector<int> w) {
  std::priority_queue<long long, std::vector<long long>,
                      std::greater<long long>>
      q;
  for (int x : w) {
    if (x < 0)
      throw std::invalid_argument("negative weight");
    q.push(x);
  }
  long long cost = 0;
  while (q.size() > 1) {
    auto a = q.top();
    q.pop();
    auto b = q.top();
    q.pop();
    cost += a + b;
    q.push(a + b);
  }
  return cost;
}
int main() {
  std::size_t pos = 0;
  auto t = build({1, 2, 4, 5, 3}, {4, 2, 5, 1, 3}, pos, 0, 5);
  assert(pos == 5 && height(t.get()) == 3);
  std::vector<int> post;
  postorder(t.get(), post);
  assert((post == std::vector<int>{4, 5, 2, 3, 1}));
  assert((level(t.get()) == std::vector<int>{1, 2, 3, 4, 5}));
  assert(height(nullptr) == 0 && level(nullptr).empty());
  assert(huffmanCost({1, 2, 3, 6}) == 21 && huffmanCost({}) == 0 &&
         huffmanCost({5}) == 0);
  std::cout << "chapter05: passed\n";
}
