Skip to content

rectangle_add_point_get.hpp

SECTIONData Structure INCLUDEnoya/ds/rectangle_add_point_get.hpp

对多个轴对齐矩形整体加权,并查询指定点累计受到的贡献;适合矩形覆盖、点询问模型。

Complexity: Time: \(O(r \log (r + 1))\) preprocessing and \(O(\log^{2} (r + 1))\) per rectangle addition or point query; the batch helper is \(O((R + Q) \log (R + Q))\) with the default Fenwick backend (custom \(C\) follows its operation costs). Space: \(O(r \log r)\) for the dynamic structure and \(O(R + Q)\) for the helper.

AC 记录:rectangle_add_point_get。

跳到代码 · GitHub ↗

Implementation

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

/// @complexity Time: O(r log(r+1)) preprocessing and O(log^2(r+1)) per rectangle
/// addition or point query; the batch helper is O((R + Q) log(R + Q))
/// with the default Fenwick backend (custom C follows its operation costs).
/// Space: O(r log r) for the dynamic structure and O(R + Q) for the helper.

#include "noya/ds/point_add_range_sum.hpp"
#include "noya/ds/sparse_fenwick_2d.hpp"

#include <algorithm>
#include <array>
#include <cstddef>
#include <vector>

namespace noya {

/// @brief Rectangle-add point-get data structure on sparse coordinates.
/// A half-open rectangle update is its four-corner two-dimensional difference;
/// the value at a point is the inclusive prefix sum of those differences.
/// Register all rectangles before build(), including rectangles added later.
template <class T, class Coordinate = int> struct rectangle_add_point_get_tree {
  sparse_fenwick_2d<T, Coordinate> bit;

  void reserve_rectangle(Coordinate L, Coordinate dn, Coordinate R,
                         Coordinate up) {
    if (L == R || dn == up) {
      return;
    }
    bit.reserve(L, dn);
    bit.reserve(L, up);
    bit.reserve(R, dn);
    bit.reserve(R, up);
  }

  void build() { bit.build(); }

  void add_rectangle(Coordinate L, Coordinate dn, Coordinate R,
                     Coordinate up, const T &dif) {
    if (L == R || dn == up) {
      return;
    }
    bit.add(L, dn, dif);
    bit.add(L, up, -dif);
    bit.add(R, dn, -dif);
    bit.add(R, up, dif);
  }

  T point_get(Coordinate x, Coordinate y) const {
    return bit.prefix_sum_inclusive(x, y);
  }
};

/// @brief Offline rectangle-add point-get queries.
/// Add weight w to [l, r) x [d, u), then return the value at every point.
/// Sweep the two vertical edges of each rectangle, maintaining y differences.
/// Coordinates may be negative; weights and their negations are computed in T.
template <class T, class C = noya::fenwick<T>>
std::vector<T>
rectangle_add_point_get(std::vector<std::array<int, 5>> rs,
                        std::vector<std::array<int, 2>> pt) {
  std::vector<T> ans(pt.size());
  if (pt.empty()) {
    return ans;
  }
  std::vector<int> ys;
  ys.reserve(rs.size() * 2);
  for (auto [l, r, d, u, w] : rs) {
    if (l == r || d == u) {
      continue;
    }
    ys.push_back(d);
    ys.push_back(u);
  }
  if (ys.empty()) {
    return ans;
  }
  std::sort(ys.begin(), ys.end());
  ys.erase(std::unique(ys.begin(), ys.end()), ys.end());

  // Right edges swap the y boundaries instead of negating an int weight.
  std::vector<std::array<int, 4>> es;
  es.reserve(rs.size() * 2);
  for (auto [l, r, d, u, w] : rs) {
    if (l == r || d == u) {
      continue;
    }
    int a = int(std::lower_bound(ys.begin(), ys.end(), d) - ys.begin());
    int b = int(std::lower_bound(ys.begin(), ys.end(), u) - ys.begin());
    es.push_back({l, a, b, w});
    es.push_back({r, b, a, w});
  }
  std::sort(es.begin(), es.end(),
            [](const auto &a, const auto &b) { return a[0] < b[0]; });
  std::vector<std::array<int, 3>> qs;
  qs.reserve(pt.size());
  for (int i = 0; i < int(pt.size()); ++i) {
    qs.push_back({pt[i][0], pt[i][1], i});
  }
  std::sort(qs.begin(), qs.end(),
            [](const auto &a, const auto &b) { return a[0] < b[0]; });

  C bit(int(ys.size()));
  std::size_t ei = 0;
  for (auto [x, y, i] : qs) {
    while (ei < es.size() && es[ei][0] <= x) {
      auto [edge_x, a, b, w] = es[ei++];
      T delta(w);
      bit.add(a, delta);
      bit.add(b, -delta);
    }
    int end = int(std::upper_bound(ys.begin(), ys.end(), y) - ys.begin());
    ans[i] = bit.prod(0, end);
  }
  return ans;
}

} // namespace noya

 // NOYA_RECTANGLE_ADD_POINT_GET_HPP
#ifndef NOYA_RECTANGLE_ADD_POINT_GET_HPP
#define NOYA_RECTANGLE_ADD_POINT_GET_HPP 1

/// @complexity Time: O(r log(r+1)) preprocessing and O(log^2(r+1)) per rectangle
/// addition or point query; the batch helper is O((R + Q) log(R + Q))
/// with the default Fenwick backend (custom C follows its operation costs).
/// Space: O(r log r) for the dynamic structure and O(R + Q) for the helper.

#include "noya/ds/point_add_range_sum.hpp"
#include "noya/ds/sparse_fenwick_2d.hpp"

#include <algorithm>
#include <array>
#include <cstddef>
#include <vector>

namespace noya {

/// @brief Rectangle-add point-get data structure on sparse coordinates.
/// A half-open rectangle update is its four-corner two-dimensional difference;
/// the value at a point is the inclusive prefix sum of those differences.
/// Register all rectangles before build(), including rectangles added later.
template <class T, class Coordinate = int> struct rectangle_add_point_get_tree {
  sparse_fenwick_2d<T, Coordinate> bit;

  void reserve_rectangle(Coordinate L, Coordinate dn, Coordinate R,
                         Coordinate up) {
    if (L == R || dn == up) {
      return;
    }
    bit.reserve(L, dn);
    bit.reserve(L, up);
    bit.reserve(R, dn);
    bit.reserve(R, up);
  }

  void build() { bit.build(); }

  void add_rectangle(Coordinate L, Coordinate dn, Coordinate R,
                     Coordinate up, const T &dif) {
    if (L == R || dn == up) {
      return;
    }
    bit.add(L, dn, dif);
    bit.add(L, up, -dif);
    bit.add(R, dn, -dif);
    bit.add(R, up, dif);
  }

  T point_get(Coordinate x, Coordinate y) const {
    return bit.prefix_sum_inclusive(x, y);
  }
};

/// @brief Offline rectangle-add point-get queries.
/// Add weight w to [l, r) x [d, u), then return the value at every point.
/// Sweep the two vertical edges of each rectangle, maintaining y differences.
/// Coordinates may be negative; weights and their negations are computed in T.
template <class T, class C = noya::fenwick<T>>
std::vector<T>
rectangle_add_point_get(std::vector<std::array<int, 5>> rs,
                        std::vector<std::array<int, 2>> pt) {
  std::vector<T> ans(pt.size());
  if (pt.empty()) {
    return ans;
  }
  std::vector<int> ys;
  ys.reserve(rs.size() * 2);
  for (auto [l, r, d, u, w] : rs) {
    if (l == r || d == u) {
      continue;
    }
    ys.push_back(d);
    ys.push_back(u);
  }
  if (ys.empty()) {
    return ans;
  }
  std::sort(ys.begin(), ys.end());
  ys.erase(std::unique(ys.begin(), ys.end()), ys.end());

  // Right edges swap the y boundaries instead of negating an int weight.
  std::vector<std::array<int, 4>> es;
  es.reserve(rs.size() * 2);
  for (auto [l, r, d, u, w] : rs) {
    if (l == r || d == u) {
      continue;
    }
    int a = int(std::lower_bound(ys.begin(), ys.end(), d) - ys.begin());
    int b = int(std::lower_bound(ys.begin(), ys.end(), u) - ys.begin());
    es.push_back({l, a, b, w});
    es.push_back({r, b, a, w});
  }
  std::sort(es.begin(), es.end(),
            [](const auto &a, const auto &b) { return a[0] < b[0]; });
  std::vector<std::array<int, 3>> qs;
  qs.reserve(pt.size());
  for (int i = 0; i < int(pt.size()); ++i) {
    qs.push_back({pt[i][0], pt[i][1], i});
  }
  std::sort(qs.begin(), qs.end(),
            [](const auto &a, const auto &b) { return a[0] < b[0]; });

  C bit(int(ys.size()));
  std::size_t ei = 0;
  for (auto [x, y, i] : qs) {
    while (ei < es.size() && es[ei][0] <= x) {
      auto [edge_x, a, b, w] = es[ei++];
      T delta(w);
      bit.add(a, delta);
      bit.add(b, -delta);
    }
    int end = int(std::upper_bound(ys.begin(), ys.end(), y) - ys.begin());
    ans[i] = bit.prod(0, end);
  }
  return ans;
}

} // namespace noya

#endif // NOYA_RECTANGLE_ADD_POINT_GET_HPP
/// @complexity Time: O(r log(r+1)) preprocessing and O(log^2(r+1)) per rectangle
/// addition or point query; the batch helper is O((R + Q) log(R + Q))
/// with the default Fenwick backend (custom C follows its operation costs).
/// Space: O(r log r) for the dynamic structure and O(R + Q) for the helper.

/// @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

/// @complexity Time: amortized O(1) registration, O(p log(p+1)) build and
/// O(log^2(p+1)) addition/query. Space: O(1 + p log(p+1)) cells.

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

namespace noya {

/// @brief Offline-built sparse two-dimensional Fenwick tree.
/// Register every coordinate that may later be updated, then call build().
/// An x-Fenwick node stores only the registered y-coordinates contributing to
/// it, so the dense coordinate plane is replaced by O(p log p) cells.
template <class T, class Coordinate = int> struct sparse_fenwick_2d {
  std::vector<std::pair<Coordinate, Coordinate>> pt;
  std::vector<Coordinate> xs;
  std::vector<std::vector<Coordinate>> ys;
  std::vector<std::vector<T>> dat;
  bool ok = false;

  /// @brief Remove all registered coordinates and values.
  void clear() {
    pt.clear();
    xs.clear();
    ys.clear();
    dat.clear();
    ok = false;
  }

  /// @brief Register a coordinate that may be passed to add() after build().
  void reserve(Coordinate x, Coordinate y) {
    assert(!ok);
    pt.emplace_back(x, y);
  }

  /// @brief Build the compressed Fenwick nodes with every value initially zero.
  void build() {
    assert(!ok);
    xs.reserve(pt.size());
    for (auto [x, y] : pt) {
      (void)y;
      xs.push_back(x);
    }
    std::sort(xs.begin(), xs.end());
    xs.erase(std::unique(xs.begin(), xs.end()), xs.end());
    ys.assign(xs.size() + 1, {});
    // Global y order makes every node's coordinate list sorted as it is built.
    std::sort(pt.begin(), pt.end(), [](const auto &a, const auto &b) {
      return a.second < b.second;
    });
    for (const auto &[x, y] : pt) {
      int idx = int(std::lower_bound(xs.begin(), xs.end(), x) - xs.begin());
      for (idx++; idx <= int(xs.size()); idx += idx & -idx) {
        // A previous visit with this y also populated every higher ancestor.
        if (!ys[idx].empty() && ys[idx].back() == y) break;
        ys[idx].push_back(y);
      }
    }
    dat.resize(xs.size() + 1);
    for (int idx = 1; idx <= int(xs.size()); idx++) {
      dat[idx].assign(ys[idx].size() + 1, T{});
    }
    pt.clear();
    pt.shrink_to_fit();
    ok = true;
  }

  /// @brief Add delta at a coordinate registered before build().
  void add(Coordinate x, Coordinate y, const T &dif) {
    assert(ok);
    auto ix = std::lower_bound(xs.begin(), xs.end(), x);
    assert(ix != xs.end() && *ix == x);
    int xi = int(ix - xs.begin()) + 1;
    for (; xi <= int(xs.size()); xi += xi & -xi) {
      auto iy = std::lower_bound(ys[xi].begin(), ys[xi].end(), y);
      assert(iy != ys[xi].end() && *iy == y);
      int yi = int(iy - ys[xi].begin()) + 1;
      for (; yi < int(dat[xi].size()); yi += yi & -yi) {
        dat[xi][yi] += dif;
      }
    }
  }

  /// @brief Sum values at coordinates (px, py) with px < x and py < y.
  T prefix_sum(Coordinate x, Coordinate y) const {
    assert(ok);
    int xi = int(std::lower_bound(xs.begin(), xs.end(), x) - xs.begin());
    T res{};
    for (; xi > 0; xi -= xi & -xi) {
      int yi = int(std::lower_bound(ys[xi].begin(), ys[xi].end(), y) -
                   ys[xi].begin());
      for (; yi > 0; yi -= yi & -yi) {
        res += dat[xi][yi];
      }
    }
    return res;
  }

  /// @brief Sum values at coordinates (px, py) with px <= x and py <= y.
  T prefix_sum_inclusive(Coordinate x, Coordinate y) const {
    assert(ok);
    int xi = int(std::upper_bound(xs.begin(), xs.end(), x) - xs.begin());
    T res{};
    for (; xi > 0; xi -= xi & -xi) {
      int yi = int(std::upper_bound(ys[xi].begin(), ys[xi].end(), y) -
                   ys[xi].begin());
      for (; yi > 0; yi -= yi & -yi) {
        res += dat[xi][yi];
      }
    }
    return res;
  }

  /// @brief Sum values in [l, r) x [dn, up).
  T rectangle_sum(Coordinate l, Coordinate r, Coordinate dn,
                  Coordinate up) const {
    assert(ok);
    if (l == r || dn == up) return T{};
    int xl = int(std::lower_bound(xs.begin(), xs.end(), l) - xs.begin());
    int xr = int(std::lower_bound(xs.begin(), xs.end(), r) - xs.begin());
    // Cancel shared ancestors of the two prefix paths in each dimension.
    auto row_sum = [&](int x) {
      const auto &v = ys[x];
      int a = int(std::lower_bound(v.begin(), v.end(), dn) - v.begin());
      int b = int(std::lower_bound(v.begin(), v.end(), up) - v.begin());
      T sum{};
      while (a != b) {
        if (a < b) {
          sum += dat[x][b];
          b -= b & -b;
        } else {
          sum = sum - dat[x][a];
          a -= a & -a;
        }
      }
      return sum;
    };
    T sum{};
    while (xl != xr) {
      if (xl < xr) {
        sum += row_sum(xr);
        xr -= xr & -xr;
      } else {
        sum = sum - row_sum(xl);
        xl -= xl & -xl;
      }
    }
    return sum;
  }
};

} // namespace noya

#include <algorithm>
#include <array>
#include <cstddef>
#include <vector>

namespace noya {

/// @brief Rectangle-add point-get data structure on sparse coordinates.
/// A half-open rectangle update is its four-corner two-dimensional difference;
/// the value at a point is the inclusive prefix sum of those differences.
/// Register all rectangles before build(), including rectangles added later.
template <class T, class Coordinate = int> struct rectangle_add_point_get_tree {
  sparse_fenwick_2d<T, Coordinate> bit;

  void reserve_rectangle(Coordinate L, Coordinate dn, Coordinate R,
                         Coordinate up) {
    if (L == R || dn == up) {
      return;
    }
    bit.reserve(L, dn);
    bit.reserve(L, up);
    bit.reserve(R, dn);
    bit.reserve(R, up);
  }

  void build() { bit.build(); }

  void add_rectangle(Coordinate L, Coordinate dn, Coordinate R,
                     Coordinate up, const T &dif) {
    if (L == R || dn == up) {
      return;
    }
    bit.add(L, dn, dif);
    bit.add(L, up, -dif);
    bit.add(R, dn, -dif);
    bit.add(R, up, dif);
  }

  T point_get(Coordinate x, Coordinate y) const {
    return bit.prefix_sum_inclusive(x, y);
  }
};

/// @brief Offline rectangle-add point-get queries.
/// Add weight w to [l, r) x [d, u), then return the value at every point.
/// Sweep the two vertical edges of each rectangle, maintaining y differences.
/// Coordinates may be negative; weights and their negations are computed in T.
template <class T, class C = noya::fenwick<T>>
std::vector<T>
rectangle_add_point_get(std::vector<std::array<int, 5>> rs,
                        std::vector<std::array<int, 2>> pt) {
  std::vector<T> ans(pt.size());
  if (pt.empty()) {
    return ans;
  }
  std::vector<int> ys;
  ys.reserve(rs.size() * 2);
  for (auto [l, r, d, u, w] : rs) {
    if (l == r || d == u) {
      continue;
    }
    ys.push_back(d);
    ys.push_back(u);
  }
  if (ys.empty()) {
    return ans;
  }
  std::sort(ys.begin(), ys.end());
  ys.erase(std::unique(ys.begin(), ys.end()), ys.end());

  // Right edges swap the y boundaries instead of negating an int weight.
  std::vector<std::array<int, 4>> es;
  es.reserve(rs.size() * 2);
  for (auto [l, r, d, u, w] : rs) {
    if (l == r || d == u) {
      continue;
    }
    int a = int(std::lower_bound(ys.begin(), ys.end(), d) - ys.begin());
    int b = int(std::lower_bound(ys.begin(), ys.end(), u) - ys.begin());
    es.push_back({l, a, b, w});
    es.push_back({r, b, a, w});
  }
  std::sort(es.begin(), es.end(),
            [](const auto &a, const auto &b) { return a[0] < b[0]; });
  std::vector<std::array<int, 3>> qs;
  qs.reserve(pt.size());
  for (int i = 0; i < int(pt.size()); ++i) {
    qs.push_back({pt[i][0], pt[i][1], i});
  }
  std::sort(qs.begin(), qs.end(),
            [](const auto &a, const auto &b) { return a[0] < b[0]; });

  C bit(int(ys.size()));
  std::size_t ei = 0;
  for (auto [x, y, i] : qs) {
    while (ei < es.size() && es[ei][0] <= x) {
      auto [edge_x, a, b, w] = es[ei++];
      T delta(w);
      bit.add(a, delta);
      bit.add(b, -delta);
    }
    int end = int(std::upper_bound(ys.begin(), ys.end(), y) - ys.begin());
    ans[i] = bit.prod(0, end);
  }
  return ans;
}

} // namespace noya

 // NOYA_RECTANGLE_ADD_POINT_GET_HPP