Program Listing for File factorizer_helpers.hpp

↰ Return to documentation for file (src/cpp/factorizer_helpers.hpp)

#pragma once
#include <sdsl/suffix_trees.hpp>
#include <sdsl/wavelet_trees.hpp>
#include <sdsl/wt_algorithm.hpp>
#include <algorithm>
#include <cstdint>
#include <tuple>

namespace noLZSS {

using cst_t = sdsl::cst_sada<>;

inline size_t lcp(const cst_t& cst, size_t i, size_t j) {
    if (i == j) return cst.csa.size() - cst.csa[i];
    auto lca = cst.lca(cst.select_leaf(cst.csa.isa[i]+1), cst.select_leaf(cst.csa.isa[j]+1));
    return cst.depth(lca);
}

inline cst_t::node_type next_leaf(const cst_t& cst, cst_t::node_type lambda, size_t iterations = 1) {
    auto lambda_rank = cst.lb(lambda);
    for (size_t i = 0; i < iterations; i++) {
        lambda_rank = cst.csa.psi[lambda_rank];
    }
    return cst.select_leaf(lambda_rank + 1);
}

class RangePredecessor {
public:
    using wt_type = sdsl::wt_int<sdsl::bit_vector,
                                 sdsl::rank_support_v5<1>,
                                 sdsl::select_support_scan<1>,
                                 sdsl::select_support_scan<0>>;

    RangePredecessor() = default;

    RangePredecessor(const sdsl::int_vector<64>& values, uint64_t cap) : m_cap(cap) {
        sdsl::int_vector<64> clamped(values.size(), 0);
        for (size_t k = 0; k < values.size(); ++k) {
            uint64_t v = values[k];
            clamped[k] = v < cap ? v : cap;
        }
        m_wt = wt_type(clamped.begin(), clamped.end());
    }

    bool predecessor(size_t lb, size_t rb, uint64_t limit, uint64_t& out) const {
        if (m_cap == 0 || lb > rb) return false;
        if (limit >= m_cap) limit = m_cap - 1;             // values equal to cap are absent
        auto counts = m_wt.lex_count(lb, rb + 1, limit + 1); // (rank, #smaller than limit+1, #greater)
        size_t cnt = std::get<1>(counts);                  // == number of values <= limit
        if (cnt == 0) return false;
        out = sdsl::quantile_freq(m_wt, lb, rb, cnt - 1).first;
        return true;
    }

    bool empty() const { return m_cap == 0; }

private:
    wt_type  m_wt;
    uint64_t m_cap = 0;
};

} // namespace noLZSS