Skip to content

prefix_substring_lcs.hpp

SECTIONString INCLUDEnoya/string/prefix_substring_lcs.hpp

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

Complexity: Time: \(O(M N + (K N + Q) \log (N + 1) + M + N + Q)\). Space: \(O(M + N + Q)\). \(M / N\) are the largest nontrivial queried prefix/right boundary, \(K\) the number of such prefixes, and \(Q\) the total query count.

Source: Library Checker

AC 记录:prefix_substring_lcs。

跳到代码 · GitHub ↗

Implementation

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

// SPDX-License-Identifier: Apache-2.0
// Adapted from Library Checker, with changes for libra.
// Sources and license: third_party/README.md.

/// @complexity Time: O(M N + (K N + Q) log(N + 1) + M + N + Q).
/// Space: O(M + N + Q). M/N are the largest nontrivial queried prefix/right
/// boundary, K the number of such prefixes, and Q the total query count.

#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 j < right with to[j] >= 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;
  int width = 0;
  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) {
      if (int(by.size()) < pre) by.resize(pre);
      by[pre - 1].push_back(id);
      width = std::max(width, r);
    }
  }
  if (width == 0) return ans;

  std::vector<int> to(width);
  std::iota(to.begin(), to.end(), 0);
  std::vector<std::vector<int>> byr(width);
  int remaining = width;
  for (int pos = 0; pos < int(by.size()); pos++) {
    int old = -1;
    for (int po1 = 0; po1 < width; po1++) {
      if (a[pos] == b[po1] || to[po1] < old) {
        std::swap(to[po1], old);
      }
    }
    remaining -= old != -1;
    if (remaining == 0) { // b[0:width] is now a subsequence of a[0:pos+1].
      for (int id = 0; id < qn; id++) {
        if (qs[id].pre >= pos + 1) ans[id] = qs[id].r - qs[id].l;
      }
      break;
    }
    if (by[pos].empty()) continue;
    int last = 0;
    for (int id : by[pos]) {
      byr[qs[id].r - 1].push_back(id);
      last = std::max(last, qs[id].r);
    }

    atcoder::fenwick_tree<int> act(last); // to[r] <= r, so last also bounds updates.
    int cnt = 0;
    for (int r = 0; r < last; 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

 // NOYA_PREFIX_SUBSTRING_LCS_HPP
#ifndef NOYA_PREFIX_SUBSTRING_LCS_HPP
#define NOYA_PREFIX_SUBSTRING_LCS_HPP 1

// SPDX-License-Identifier: Apache-2.0
// Adapted from Library Checker, with changes for libra.
// Sources and license: third_party/README.md.

/// @complexity Time: O(M N + (K N + Q) log(N + 1) + M + N + Q).
/// Space: O(M + N + Q). M/N are the largest nontrivial queried prefix/right
/// boundary, K the number of such prefixes, and Q the total query count.

#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 j < right with to[j] >= 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;
  int width = 0;
  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) {
      if (int(by.size()) < pre) by.resize(pre);
      by[pre - 1].push_back(id);
      width = std::max(width, r);
    }
  }
  if (width == 0) return ans;

  std::vector<int> to(width);
  std::iota(to.begin(), to.end(), 0);
  std::vector<std::vector<int>> byr(width);
  int remaining = width;
  for (int pos = 0; pos < int(by.size()); pos++) {
    int old = -1;
    for (int po1 = 0; po1 < width; po1++) {
      if (a[pos] == b[po1] || to[po1] < old) {
        std::swap(to[po1], old);
      }
    }
    remaining -= old != -1;
    if (remaining == 0) { // b[0:width] is now a subsequence of a[0:pos+1].
      for (int id = 0; id < qn; id++) {
        if (qs[id].pre >= pos + 1) ans[id] = qs[id].r - qs[id].l;
      }
      break;
    }
    if (by[pos].empty()) continue;
    int last = 0;
    for (int id : by[pos]) {
      byr[qs[id].r - 1].push_back(id);
      last = std::max(last, qs[id].r);
    }

    atcoder::fenwick_tree<int> act(last); // to[r] <= r, so last also bounds updates.
    int cnt = 0;
    for (int r = 0; r < last; 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
// SPDX-License-Identifier: Apache-2.0
// Adapted from Library Checker, with changes for libra.
// Sources and license: third_party/README.md.

/// @complexity Time: O(M N + (K N + Q) log(N + 1) + M + N + Q).
/// Space: O(M + N + Q). M/N are the largest nontrivial queried prefix/right
/// boundary, K the number of such prefixes, and Q the total query count.

#include <cassert>
#include <vector>

#include <cassert>
#include <numeric>
#include <type_traits>

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

#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 j < right with to[j] >= 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;
  int width = 0;
  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) {
      if (int(by.size()) < pre) by.resize(pre);
      by[pre - 1].push_back(id);
      width = std::max(width, r);
    }
  }
  if (width == 0) return ans;

  std::vector<int> to(width);
  std::iota(to.begin(), to.end(), 0);
  std::vector<std::vector<int>> byr(width);
  int remaining = width;
  for (int pos = 0; pos < int(by.size()); pos++) {
    int old = -1;
    for (int po1 = 0; po1 < width; po1++) {
      if (a[pos] == b[po1] || to[po1] < old) {
        std::swap(to[po1], old);
      }
    }
    remaining -= old != -1;
    if (remaining == 0) { // b[0:width] is now a subsequence of a[0:pos+1].
      for (int id = 0; id < qn; id++) {
        if (qs[id].pre >= pos + 1) ans[id] = qs[id].r - qs[id].l;
      }
      break;
    }
    if (by[pos].empty()) continue;
    int last = 0;
    for (int id : by[pos]) {
      byr[qs[id].r - 1].push_back(id);
      last = std::max(last, qs[id].r);
    }

    atcoder::fenwick_tree<int> act(last); // to[r] <= r, so last also bounds updates.
    int cnt = 0;
    for (int r = 0; r < last; 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

 // NOYA_PREFIX_SUBSTRING_LCS_HPP