Skip to content

prefix_substring_lcs.hpp

SECTIONString INCLUDEnoya/prefix_substring_lcs.hpp

对固定串的每个前缀,求它与另一串指定子串的最长公共子序列长度。

Complexity: Time: O(m n log n + q). Space: O(n + q), for sequence lengths m, n and q offline queries.

AC 记录:prefix_substring_lcs

跳到代码 · GitHub ↗

Implementation

当前头文件,省略 include guard;依赖见 #include

/// @complexity Time: O(m n log n + q). Space: O(n + q), for sequence
/// lengths m, n and q offline queries.

#include "atcoder/fenwicktree.hpp"

#include <algorithm>
#include <cassert>
#include <numeric>
#include <vector>

namespace noya {

struct prefix_substring_lcs_query {
  int pre;
  int l;
  int r;
};

/// @brief Answer LCS lengths between prefixes of one sequence and substrings
/// of another. The dynamic-programming grid is represented by its seaweed
/// permutation: after adding one symbol of the first sequence, a single scan
/// swaps boundary endpoints exactly where equality or crossing changes the
/// next LCS row. For a fixed prefix, the LCS deficit of [left, right) equals
/// the number of active endpoints entering that interval from before left.
/// Sweeping right and counting endpoint positions with a Fenwick tree answers
/// every query assigned to that prefix without storing the quadratic DP table.
template <class FirstSequence, class SecondSequence>
std::vector<int>
prefix_substring_lcs(const FirstSequence &a, const SecondSequence &b,
                     const std::vector<prefix_substring_lcs_query> &qs) {
  int n1 = int(a.size());
  int n2 = int(b.size());
  int qn = int(qs.size());
  std::vector<int> ans(qn);
  std::vector<std::vector<int>> by(n1);
  for (int id = 0; id < qn; id++) {
    auto [pre, l, r] = qs[id];
    assert(0 <= pre && pre <= n1);
    assert(0 <= l && l <= r && r <= n2);
    if (pre != 0 && l != r) {
      by[pre - 1].push_back(id);
    }
  }

  std::vector<int> to(n2);
  std::iota(to.begin(), to.end(), 0);
  std::vector<std::vector<int>> byr(n2);
  for (int pos = 0; pos < n1; pos++) {
    int old = -1;
    for (int po1 = 0; po1 < n2; po1++) {
      if (a[pos] == b[po1] || to[po1] < old) {
        std::swap(to[po1], old);
      }
    }
    for (int id : by[pos]) {
      byr[qs[id].r - 1].push_back(id);
    }

    atcoder::fenwick_tree<int> act(n2);
    int cnt = 0;
    for (int r = 0; r < n2; r++) {
      if (to[r] != -1) {
        act.add(to[r], 1);
        cnt++;
      }
      for (int id : byr[r]) {
        int l = qs[id].l;
        int len = qs[id].r - l;
        ans[id] = len - (cnt - act.sum(0, l));
      }
      byr[r].clear();
    }
  }
  return ans;
}

} // namespace noya
#ifndef NOYA_PREFIX_SUBSTRING_LCS_HPP
#define NOYA_PREFIX_SUBSTRING_LCS_HPP 1

/// @complexity Time: O(m n log n + q). Space: O(n + q), for sequence
/// lengths m, n and q offline queries.

#include "atcoder/fenwicktree.hpp"

#include <algorithm>
#include <cassert>
#include <numeric>
#include <vector>

namespace noya {

struct prefix_substring_lcs_query {
  int pre;
  int l;
  int r;
};

/// @brief Answer LCS lengths between prefixes of one sequence and substrings
/// of another. The dynamic-programming grid is represented by its seaweed
/// permutation: after adding one symbol of the first sequence, a single scan
/// swaps boundary endpoints exactly where equality or crossing changes the
/// next LCS row. For a fixed prefix, the LCS deficit of [left, right) equals
/// the number of active endpoints entering that interval from before left.
/// Sweeping right and counting endpoint positions with a Fenwick tree answers
/// every query assigned to that prefix without storing the quadratic DP table.
template <class FirstSequence, class SecondSequence>
std::vector<int>
prefix_substring_lcs(const FirstSequence &a, const SecondSequence &b,
                     const std::vector<prefix_substring_lcs_query> &qs) {
  int n1 = int(a.size());
  int n2 = int(b.size());
  int qn = int(qs.size());
  std::vector<int> ans(qn);
  std::vector<std::vector<int>> by(n1);
  for (int id = 0; id < qn; id++) {
    auto [pre, l, r] = qs[id];
    assert(0 <= pre && pre <= n1);
    assert(0 <= l && l <= r && r <= n2);
    if (pre != 0 && l != r) {
      by[pre - 1].push_back(id);
    }
  }

  std::vector<int> to(n2);
  std::iota(to.begin(), to.end(), 0);
  std::vector<std::vector<int>> byr(n2);
  for (int pos = 0; pos < n1; pos++) {
    int old = -1;
    for (int po1 = 0; po1 < n2; po1++) {
      if (a[pos] == b[po1] || to[po1] < old) {
        std::swap(to[po1], old);
      }
    }
    for (int id : by[pos]) {
      byr[qs[id].r - 1].push_back(id);
    }

    atcoder::fenwick_tree<int> act(n2);
    int cnt = 0;
    for (int r = 0; r < n2; r++) {
      if (to[r] != -1) {
        act.add(to[r], 1);
        cnt++;
      }
      for (int id : byr[r]) {
        int l = qs[id].l;
        int len = qs[id].r - l;
        ans[id] = len - (cnt - act.sum(0, l));
      }
      byr[r].clear();
    }
  }
  return ans;
}

} // namespace noya

#endif // NOYA_PREFIX_SUBSTRING_LCS_HPP
#include <algorithm>
#include <cassert>
#include <numeric>
#include <type_traits>
#include <vector>

/// @complexity Time: O(m n log n + q). Space: O(n + q), for sequence
/// lengths m, n and q offline queries.

namespace atcoder {

namespace internal {

#ifndef _MSC_VER
template <class T>
using is_signed_int128 =
    typename std::conditional<std::is_same<T, __int128_t>::value ||
                                  std::is_same<T, __int128>::value,
                              std::true_type,
                              std::false_type>::type;

template <class T>
using is_unsigned_int128 =
    typename std::conditional<std::is_same<T, __uint128_t>::value ||
                                  std::is_same<T, unsigned __int128>::value,
                              std::true_type,
                              std::false_type>::type;

template <class T>
using make_unsigned_int128 =
    typename std::conditional<std::is_same<T, __int128_t>::value,
                              __uint128_t,
                              unsigned __int128>;

template <class T>
using is_integral = typename std::conditional<std::is_integral<T>::value ||
                                                  is_signed_int128<T>::value ||
                                                  is_unsigned_int128<T>::value,
                                              std::true_type,
                                              std::false_type>::type;

template <class T>
using is_signed_int = typename std::conditional<(is_integral<T>::value &&
                                                 std::is_signed<T>::value) ||
                                                    is_signed_int128<T>::value,
                                                std::true_type,
                                                std::false_type>::type;

template <class T>
using is_unsigned_int =
    typename std::conditional<(is_integral<T>::value &&
                               std::is_unsigned<T>::value) ||
                                  is_unsigned_int128<T>::value,
                              std::true_type,
                              std::false_type>::type;

template <class T>
using to_unsigned = typename std::conditional<
    is_signed_int128<T>::value,
    make_unsigned_int128<T>,
    typename std::conditional<std::is_signed<T>::value,
                              std::make_unsigned<T>,
                              std::common_type<T>>::type>::type;

#else

template <class T> using is_integral = typename std::is_integral<T>;

template <class T>
using is_signed_int =
    typename std::conditional<is_integral<T>::value && std::is_signed<T>::value,
                              std::true_type,
                              std::false_type>::type;

template <class T>
using is_unsigned_int =
    typename std::conditional<is_integral<T>::value &&
                                  std::is_unsigned<T>::value,
                              std::true_type,
                              std::false_type>::type;

template <class T>
using to_unsigned = typename std::conditional<is_signed_int<T>::value,
                                              std::make_unsigned<T>,
                                              std::common_type<T>>::type;

#endif

template <class T>
using is_signed_int_t = std::enable_if_t<is_signed_int<T>::value>;

template <class T>
using is_unsigned_int_t = std::enable_if_t<is_unsigned_int<T>::value>;

template <class T> using to_unsigned_t = typename to_unsigned<T>::type;

}  // namespace internal

}  // namespace atcoder

namespace atcoder {

// Reference: https://en.wikipedia.org/wiki/Fenwick_tree
template <class T> struct fenwick_tree {
    using U = internal::to_unsigned_t<T>;

  public:
    fenwick_tree() : _n(0) {}
    explicit fenwick_tree(int n) : _n(n), data(n) {}

    void add(int p, T x) {
        assert(0 <= p && p < _n);
        p++;
        while (p <= _n) {
            data[p - 1] += U(x);
            p += p & -p;
        }
    }

    T sum(int l, int r) {
        assert(0 <= l && l <= r && r <= _n);
        return sum(r) - sum(l);
    }

  private:
    int _n;
    std::vector<U> data;

    U sum(int r) {
        U s = 0;
        while (r > 0) {
            s += data[r - 1];
            r -= r & -r;
        }
        return s;
    }
};

}  // namespace atcoder

namespace noya {

struct prefix_substring_lcs_query {
  int pre;
  int l;
  int r;
};

/// @brief Answer LCS lengths between prefixes of one sequence and substrings
/// of another. The dynamic-programming grid is represented by its seaweed
/// permutation: after adding one symbol of the first sequence, a single scan
/// swaps boundary endpoints exactly where equality or crossing changes the
/// next LCS row. For a fixed prefix, the LCS deficit of [left, right) equals
/// the number of active endpoints entering that interval from before left.
/// Sweeping right and counting endpoint positions with a Fenwick tree answers
/// every query assigned to that prefix without storing the quadratic DP table.
template <class FirstSequence, class SecondSequence>
std::vector<int>
prefix_substring_lcs(const FirstSequence &a, const SecondSequence &b,
                     const std::vector<prefix_substring_lcs_query> &qs) {
  int n1 = int(a.size());
  int n2 = int(b.size());
  int qn = int(qs.size());
  std::vector<int> ans(qn);
  std::vector<std::vector<int>> by(n1);
  for (int id = 0; id < qn; id++) {
    auto [pre, l, r] = qs[id];
    assert(0 <= pre && pre <= n1);
    assert(0 <= l && l <= r && r <= n2);
    if (pre != 0 && l != r) {
      by[pre - 1].push_back(id);
    }
  }

  std::vector<int> to(n2);
  std::iota(to.begin(), to.end(), 0);
  std::vector<std::vector<int>> byr(n2);
  for (int pos = 0; pos < n1; pos++) {
    int old = -1;
    for (int po1 = 0; po1 < n2; po1++) {
      if (a[pos] == b[po1] || to[po1] < old) {
        std::swap(to[po1], old);
      }
    }
    for (int id : by[pos]) {
      byr[qs[id].r - 1].push_back(id);
    }

    atcoder::fenwick_tree<int> act(n2);
    int cnt = 0;
    for (int r = 0; r < n2; r++) {
      if (to[r] != -1) {
        act.add(to[r], 1);
        cnt++;
      }
      for (int id : byr[r]) {
        int l = qs[id].l;
        int len = qs[id].r - l;
        ans[id] = len - (cnt - act.sum(0, l));
      }
      byr[r].clear();
    }
  }
  return ans;
}

} // namespace noya