A Forest is a view of a sorted range which carries an ancestry relation in addition to an ordering relation: each element's descendants appear directly after it. This can be used to efficiently skip subtrees when iterating through the range.
| 31 | /// to an ordering relation: each element's descendants appear directly after it. |
| 32 | /// This can be used to efficiently skip subtrees when iterating through the range. |
| 33 | class Forest { |
| 34 | public: |
| 35 | Forest() = default; |
| 36 | |
| 37 | /// \brief Construct a Forest viewing the range [0, size). |
| 38 | Forest(int size, std::function<bool(int, int)> is_ancestor) : size_(size) { |
| 39 | std::vector<int> descendant_counts(size, 0); |
| 40 | |
| 41 | std::vector<int> parent_stack; |
| 42 | |
| 43 | for (int i = 0; i < size; ++i) { |
| 44 | while (parent_stack.size() != 0) { |
| 45 | if (is_ancestor(parent_stack.back(), i)) break; |
| 46 | |
| 47 | // parent_stack.back() has no more descendants; finalize count and pop |
| 48 | descendant_counts[parent_stack.back()] = i - 1 - parent_stack.back(); |
| 49 | parent_stack.pop_back(); |
| 50 | } |
| 51 | |
| 52 | parent_stack.push_back(i); |
| 53 | } |
| 54 | |
| 55 | // finalize descendant_counts for anything left in the stack |
| 56 | while (parent_stack.size() != 0) { |
| 57 | descendant_counts[parent_stack.back()] = size - 1 - parent_stack.back(); |
| 58 | parent_stack.pop_back(); |
| 59 | } |
| 60 | |
| 61 | descendant_counts_ = std::make_shared<std::vector<int>>(std::move(descendant_counts)); |
| 62 | } |
| 63 | |
| 64 | /// \brief Returns the number of nodes in this forest. |
| 65 | int size() const { return size_; } |
| 66 | |
| 67 | bool Equals(const Forest& other) const { |
| 68 | auto it = descendant_counts_->begin(); |
| 69 | return size_ == other.size_ && |
| 70 | std::equal(it, it + size_, other.descendant_counts_->begin()); |
| 71 | } |
| 72 | |
| 73 | struct Ref { |
| 74 | int num_descendants() const { return forest->descendant_counts_->at(i); } |
| 75 | |
| 76 | bool IsAncestorOf(const Ref& ref) const { |
| 77 | return i < ref.i && i + 1 + num_descendants() > ref.i; |
| 78 | } |
| 79 | |
| 80 | explicit operator bool() const { return forest != NULLPTR; } |
| 81 | |
| 82 | const Forest* forest; |
| 83 | int i; |
| 84 | }; |
| 85 | |
| 86 | /// \brief Visit with eager pruning. Visitors must return Result<bool>, using |
| 87 | /// true to indicate a subtree should be visited and false to indicate that the |
| 88 | /// subtree should be skipped. |
| 89 | template <typename PreVisitor, typename PostVisitor> |
| 90 | Status Visit(PreVisitor&& pre, PostVisitor&& post) const { |
no outgoing calls