Skip to content

static_range_distinct.hpp

SECTIONData Structure INCLUDEnoya/ds/static_range_distinct.hpp

回答静态数组任意区间内不同值的个数;适合大量不带修改的区间去重计数。

Complexity: Time: \(O((m + q) \log (m + 2))\) with linear stable-sort workspace. Space: \(O(1 + m + q)\), where \(m\) is the span of all nonempty queries.

AC 记录:static_range_count_distinct。

跳到代码 · GitHub ↗

Implementation

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

/// @complexity Time: O((m+q) log(m+2)) with linear stable-sort workspace.
/// Space: O(1+m+q), where m is the span of all nonempty queries.

#include "noya/ds/point_add_range_sum.hpp"

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

namespace noya {

/// @brief Count distinct values in every offline half-open range [l, r).
/// Values are grouped by ordering equivalence; bounds assume O(1) comparisons.
template <class T>
std::vector<int>
static_range_distinct(const std::vector<T> &a,
                      const std::vector<std::pair<int, int>> &qs) {
  const int n = int(a.size());
  std::vector<int> ans(qs.size());
  int first = n, end = 0;
  for (auto [l, r] : qs) {
    assert(0 <= l && l <= r && r <= n);
    if (l < r) {
      first = std::min(first, l);
      end = std::max(end, r);
    }
  }
  if (first >= end) return ans;
  const int m = end - first;

  std::vector<int> prev(m, -1);
  {
    std::vector<int> order(m);
    std::iota(order.begin(), order.end(), 0);
    // Stable ties retain position order, so adjacent equals give predecessors.
    std::stable_sort(order.begin(), order.end(),
                     [&](int i, int j) { return a[first + i] < a[first + j]; });
    for (int i = 1; i < m; ++i) {
      if (!(a[first + order[i - 1]] < a[first + order[i]]))
        prev[order[i]] = order[i - 1];
    }
  }

  std::vector<int> head(std::size_t(m) + 1, -1), next(qs.size());
  for (int id = 0; id < int(qs.size()); ++id) {
    auto [l, r] = qs[id];
    if (l == r) continue;
    r -= first;
    next[id] = head[r];
    head[r] = id;
  }

  fenwick<int> covered(m);
  int distinct = 0;
  for (int pos = 0; pos < m; ++pos) {
    if (prev[pos] == -1) ++distinct;
    else covered.add(prev[pos], 1);
    // At r=pos+1, there are r-distinct covered positions in the prefix.
    // Remove those in [l,r) from its length: distinct-l+covered.query(l).
    for (int id = head[pos + 1]; id != -1; id = next[id]) {
      int l = qs[id].first - first;
      ans[id] = distinct - l + covered.query(l);
    }
  }
  return ans;
}

} // namespace noya

 // NOYA_STATIC_RANGE_DISTINCT_HPP
#ifndef NOYA_STATIC_RANGE_DISTINCT_HPP
#define NOYA_STATIC_RANGE_DISTINCT_HPP 1

/// @complexity Time: O((m+q) log(m+2)) with linear stable-sort workspace.
/// Space: O(1+m+q), where m is the span of all nonempty queries.

#include "noya/ds/point_add_range_sum.hpp"

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

namespace noya {

/// @brief Count distinct values in every offline half-open range [l, r).
/// Values are grouped by ordering equivalence; bounds assume O(1) comparisons.
template <class T>
std::vector<int>
static_range_distinct(const std::vector<T> &a,
                      const std::vector<std::pair<int, int>> &qs) {
  const int n = int(a.size());
  std::vector<int> ans(qs.size());
  int first = n, end = 0;
  for (auto [l, r] : qs) {
    assert(0 <= l && l <= r && r <= n);
    if (l < r) {
      first = std::min(first, l);
      end = std::max(end, r);
    }
  }
  if (first >= end) return ans;
  const int m = end - first;

  std::vector<int> prev(m, -1);
  {
    std::vector<int> order(m);
    std::iota(order.begin(), order.end(), 0);
    // Stable ties retain position order, so adjacent equals give predecessors.
    std::stable_sort(order.begin(), order.end(),
                     [&](int i, int j) { return a[first + i] < a[first + j]; });
    for (int i = 1; i < m; ++i) {
      if (!(a[first + order[i - 1]] < a[first + order[i]]))
        prev[order[i]] = order[i - 1];
    }
  }

  std::vector<int> head(std::size_t(m) + 1, -1), next(qs.size());
  for (int id = 0; id < int(qs.size()); ++id) {
    auto [l, r] = qs[id];
    if (l == r) continue;
    r -= first;
    next[id] = head[r];
    head[r] = id;
  }

  fenwick<int> covered(m);
  int distinct = 0;
  for (int pos = 0; pos < m; ++pos) {
    if (prev[pos] == -1) ++distinct;
    else covered.add(prev[pos], 1);
    // At r=pos+1, there are r-distinct covered positions in the prefix.
    // Remove those in [l,r) from its length: distinct-l+covered.query(l).
    for (int id = head[pos + 1]; id != -1; id = next[id]) {
      int l = qs[id].first - first;
      ans[id] = distinct - l + covered.query(l);
    }
  }
  return ans;
}

} // namespace noya

#endif // NOYA_STATIC_RANGE_DISTINCT_HPP
/// @complexity Time: O((m+q) log(m+2)) with linear stable-sort workspace.
/// Space: O(1+m+q), where m is the span of all nonempty queries.

/// @complexity Time: fenwick O(log n) update/query; block O(1) update and
/// O(sqrt(n)) query. Both initialize in O(n).
/// Space: O(n).

#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 <cmath>
#include <vector>

namespace noya {
/// @brief Square-root decomposition for point additions and range sums.
template <class T> struct block {
  int V = 0, B = 1;

  block() = default;
  block(const int &_V) { build(_V); }

  std::vector<T> pt, blo;
  void build(const int &_V) {
    assert(_V >= 0);
    V = _V;
    B = std::max(1, int(std::sqrt(V)));
    pt.assign(V, 0);
    blo.assign(V / B + 1, 0);
  }

  void add(int x, T v) {
    assert(0 <= x && x < V);
    int bel = x / B;
    blo[bel] += v;
    pt[x] += v;
  }

  T query(int x) const {
    assert(0 <= x && x <= V);
    T res = 0;
    int bel = x / B;
    for (int i = 0; i < bel; i++)
      res += blo[i];
    int st = bel * B;
    int end = x;
    for (int i = st; i < end; i++)
      res += pt[i];
    return res;
  }

  /// @brief Sum of [l, r).
  T prod(int l, int r) const {
    assert(0 <= l && l <= r && r <= V);
    if (l == 0) {
      return query(r);
    }
    int lb = l / B, rb = r / B;
    T res = 0;
    if (lb == rb) {
      for (int i = l; i < r; ++i)
        res += pt[i];
      return res;
    }
    if (l == lb * B) {
      res += blo[lb];
    } else {
      for (int i = l; i < (lb + 1) * B; ++i)
        res += pt[i];
    }
    for (int i = lb + 1; i < rb; ++i)
      res += blo[i];
    for (int i = rb * B; i < r; ++i)
      res += pt[i];
    return res;
  }
};

/// @brief Fenwick-tree wrapper with prefix query and half-open prod aliases.
template <class T> struct fenwick : atcoder::fenwick_tree<T> {
  using atcoder::fenwick_tree<T>::fenwick_tree;
  using atcoder::fenwick_tree<T>::add;
  T query(int x) { return this->sum(0, x); }
  T prod(int l, int r) { return this->sum(l, r); }
};

} // namespace noya

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

namespace noya {

/// @brief Count distinct values in every offline half-open range [l, r).
/// Values are grouped by ordering equivalence; bounds assume O(1) comparisons.
template <class T>
std::vector<int>
static_range_distinct(const std::vector<T> &a,
                      const std::vector<std::pair<int, int>> &qs) {
  const int n = int(a.size());
  std::vector<int> ans(qs.size());
  int first = n, end = 0;
  for (auto [l, r] : qs) {
    assert(0 <= l && l <= r && r <= n);
    if (l < r) {
      first = std::min(first, l);
      end = std::max(end, r);
    }
  }
  if (first >= end) return ans;
  const int m = end - first;

  std::vector<int> prev(m, -1);
  {
    std::vector<int> order(m);
    std::iota(order.begin(), order.end(), 0);
    // Stable ties retain position order, so adjacent equals give predecessors.
    std::stable_sort(order.begin(), order.end(),
                     [&](int i, int j) { return a[first + i] < a[first + j]; });
    for (int i = 1; i < m; ++i) {
      if (!(a[first + order[i - 1]] < a[first + order[i]]))
        prev[order[i]] = order[i - 1];
    }
  }

  std::vector<int> head(std::size_t(m) + 1, -1), next(qs.size());
  for (int id = 0; id < int(qs.size()); ++id) {
    auto [l, r] = qs[id];
    if (l == r) continue;
    r -= first;
    next[id] = head[r];
    head[r] = id;
  }

  fenwick<int> covered(m);
  int distinct = 0;
  for (int pos = 0; pos < m; ++pos) {
    if (prev[pos] == -1) ++distinct;
    else covered.add(prev[pos], 1);
    // At r=pos+1, there are r-distinct covered positions in the prefix.
    // Remove those in [l,r) from its length: distinct-l+covered.query(l).
    for (int id = head[pos + 1]; id != -1; id = next[id]) {
      int l = qs[id].first - first;
      ans[id] = distinct - l + covered.query(l);
    }
  }
  return ans;
}

} // namespace noya

 // NOYA_STATIC_RANGE_DISTINCT_HPP