shogo-library

競技プログラミング用の C++ ライブラリ

View the Project on GitHub shogo314/shogo-library

:heavy_check_mark: test/aoj/dsl/dsl-4-a.1.test.cpp

Depends on

Code

#define PROBLEM "https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DSL_4_A"

#include <iostream>
#include <vector>

#include "../../../src/geometry/rectangle.hpp"
#include "../../../src/utility/container_func.hpp"
#include "../../../src/utility/range.hpp"
#include "../../../src/utility/vector_func.hpp"

int main() {
    int n;
    std::cin >> n;
    std::vector<Rectangle<long long>> rects(n);
    std::vector<long long> xs, ys;
    for (int i = 0; i < n; i++) {
        std::cin >> rects[i];
        xs.push_back(rects[i].left), xs.push_back(rects[i].right);
        ys.push_back(rects[i].bottom), ys.push_back(rects[i].top);
    }
    // 座標圧縮
    xs = unique(xs);
    ys = unique(ys);
    int w = xs.size(), h = ys.size();
    std::vector<std::vector<int>> imos(w, std::vector<int>(h));
    for (int i = 0; i < n; i++) {
        int a = bisect_left(xs, rects[i].left), b = bisect_left(xs, rects[i].right);
        int c = bisect_left(ys, rects[i].bottom), d = bisect_left(ys, rects[i].top);
        imos[a][c]++, imos[a][d]--, imos[b][c]--, imos[b][d]++;
    }
    for (auto [i, j] : Grid(Range(w), Range(1, h))) imos[i][j] += imos[i][j - 1];
    for (auto [i, j] : Grid(Range(1, w), Range(h))) imos[i][j] += imos[i - 1][j];
    long long ans = 0;
    for (auto [i, j] : Grid(w - 1, h - 1)) {
        if (imos[i][j] > 0) ans += (xs[i + 1] - xs[i]) * (ys[j + 1] - ys[j]);
    }
    std::cout << ans << '\n';
}
#line 1 "test/aoj/dsl/dsl-4-a.1.test.cpp"
#define PROBLEM "https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DSL_4_A"

#include <iostream>
#include <vector>

#line 2 "src/geometry/rectangle.hpp"

/**
 * @file rectangle.hpp
 * @brief 軸に平行な長方形
 */

#include <cassert>
#include <istream>
#include <type_traits>

#line 2 "src/geometry/vector.hpp"

/**
 * @file vector.hpp
 * @brief 幾何ベクトル
 */

#include <array>
#line 10 "src/geometry/vector.hpp"
#include <cmath>
#line 12 "src/geometry/vector.hpp"
#include <ostream>
#line 14 "src/geometry/vector.hpp"
#include <utility>

#line 2 "src/utility/traits.hpp"

/**
 * @file traits.hpp
 * @brief 型特性
 */

#include <cstddef>
#include <functional>
#include <iterator>
#include <set>
#line 14 "src/utility/traits.hpp"

#if __cplusplus >= 202002L
#include <concepts>
#include <ranges>
#endif

namespace internal_traits {
using std::begin, std::end;

#if __cplusplus >= 202002L
template <class T>
    struct is_range_impl : std::bool_constant < requires(T& t) {
    begin(t);
    end(t);
}>{};
#else
template <class T, class = void>
struct is_range_impl : std::false_type {};
template <class T>
struct is_range_impl<T, std::void_t<decltype(begin(std::declval<T&>()), end(std::declval<T&>()))>> : std::true_type {};
#endif

// サイズ付き範囲から要素を直接構築するコンストラクタで共有する。
#if __cplusplus >= 202002L
template <class R, class S>
concept sized_constructible_range = std::ranges::input_range<R> && std::ranges::sized_range<R> &&
                                    std::is_constructible_v<S, std::ranges::range_reference_t<R>>;

template <class R>
auto range_size(R& r) {
    return std::ranges::size(r);
}
template <class R>
auto range_begin(R& r) {
    return std::ranges::begin(r);
}
template <class R>
using range_value_t = std::ranges::range_value_t<R>;
#else
using std::size;
template <class R>
auto range_size(R& r) -> decltype(size(r)) {
    return size(r);
}
template <class R>
auto range_begin(R& r) -> decltype(begin(r)) {
    return begin(r);
}
template <class R>
using range_value_t = typename std::iterator_traits<decltype(range_begin(std::declval<R&>()))>::value_type;

template <class R, class S, class = void>
struct is_sized_constructible_range : std::false_type {};
template <class R, class S>
struct is_sized_constructible_range<R, S, std::void_t<decltype(range_size(std::declval<R&>())), decltype(++std::declval<decltype(begin(std::declval<R&>()))&>()), decltype(begin(std::declval<R&>()) != end(std::declval<R&>())), decltype(*begin(std::declval<R&>()))>>
    : std::is_constructible<S, decltype(*begin(std::declval<R&>()))> {};
#endif
}  // namespace internal_traits

template <class T>
struct is_range : internal_traits::is_range_impl<T>::type {};
template <class T>
inline constexpr bool is_range_v = is_range<T>::value;

#if __cplusplus >= 202002L
#define HAS_METHOD(func_name)                                                                   \
    namespace internal_traits {                                                                 \
    template <class T>                                                                          \
    concept has_##func_name##_impl = requires { std::declval<T>().func_name(); };               \
    }                                                                                           \
    template <class T>                                                                          \
    struct has_##func_name : std::bool_constant<internal_traits::has_##func_name##_impl<T>> {}; \
    template <class T>                                                                          \
    inline constexpr bool has_##func_name##_v = has_##func_name<T>::value;

#define HAS_METHOD_ARG(func_name)                                                                  \
    namespace internal_traits {                                                                    \
    template <class T, class U>                                                                    \
    concept has_##func_name##_impl = requires { std::declval<T>().func_name(std::declval<U>()); }; \
    }                                                                                              \
    template <class T, class U>                                                                    \
    struct has_##func_name : std::bool_constant<internal_traits::has_##func_name##_impl<T, U>> {}; \
    template <class T, class U>                                                                    \
    inline constexpr bool has_##func_name##_v = has_##func_name<T, U>::value;
#else
#define HAS_METHOD(func_name)                                                              \
    namespace internal_traits {                                                            \
    template <class T, class = void>                                                       \
    struct has_##func_name##_impl : std::false_type {};                                    \
    template <class T>                                                                     \
    struct has_##func_name##_impl<T, std::void_t<decltype(std::declval<T>().func_name())>> \
        : std::true_type {};                                                               \
    }                                                                                      \
    template <class T>                                                                     \
    struct has_##func_name : internal_traits::has_##func_name##_impl<T>::type {};          \
    template <class T>                                                                     \
    inline constexpr bool has_##func_name##_v = has_##func_name<T>::value;

#define HAS_METHOD_ARG(func_name)                                                                              \
    namespace internal_traits {                                                                                \
    template <class T, typename U, class = void>                                                               \
    struct has_##func_name##_impl : std::false_type {};                                                        \
    template <class T, typename U>                                                                             \
    struct has_##func_name##_impl<T, U, std::void_t<decltype(std::declval<T>().func_name(std::declval<U>()))>> \
        : std::true_type {};                                                                                   \
    }                                                                                                          \
    template <class T, typename U>                                                                             \
    struct has_##func_name : internal_traits::has_##func_name##_impl<T, U>::type {};                           \
    template <class T, typename U>                                                                             \
    inline constexpr bool has_##func_name##_v = has_##func_name<T, U>::value;
#endif

HAS_METHOD(repr)
HAS_METHOD(type_str)
HAS_METHOD(initializer_str)
HAS_METHOD(max)
HAS_METHOD(min)
HAS_METHOD(reversed)
HAS_METHOD(sorted)
HAS_METHOD(sum)
HAS_METHOD(product)
HAS_METHOD(product_xor)
HAS_METHOD_ARG(count)
HAS_METHOD_ARG(find)
HAS_METHOD_ARG(lower_bound)
HAS_METHOD_ARG(upper_bound)

#define ENABLE_IF_T_IMPL(expr) std::enable_if_t<expr, std::nullptr_t> = nullptr
#define ENABLE_IF_T(...) ENABLE_IF_T_IMPL((__VA_ARGS__))

namespace internal_traits {
// 射影 (proj) の既定値
#if __cplusplus >= 202002L
using identity = std::identity;
#else
struct identity {
    using is_transparent = void;
    template <class T>
    constexpr T&& operator()(T&& x) const noexcept {
        return std::forward<T>(x);
    }
};
#endif
}  // namespace internal_traits

template <class C>
using mem_value_type = typename C::value_type;
template <class C>
using mem_difference_type = typename C::difference_type;

namespace internal_traits {
template <class T, class = void>
struct is_sorted_container_impl : std::false_type {};
template <class T>
struct is_sorted_container_impl<std::set<T>> : std::true_type {};
template <class T>
struct is_sorted_container_impl<std::multiset<T>> : std::true_type {};
}  // namespace internal_traits
template <class T>
struct is_sorted_container : internal_traits::is_sorted_container_impl<T>::type {};
template <class T>
inline constexpr bool is_sorted_container_v = is_sorted_container<T>::value;
#line 17 "src/geometry/vector.hpp"

/**
 * @brief 幾何学としてのベクトル
 *
 * @tparam T 型 省略したらdouble
 * @tparam Dim 次元 省略したら2
 */
template <typename T = double, int Dim = 2, ENABLE_IF_T(std::is_scalar_v<T> && (Dim > 0))>
struct Vector {
    std::array<T, Dim> v;  //!< ベクトルの成分表示

    /**
     * @brief デフォルトコンストラクタ
     * ゼロベクトル
     */
    constexpr Vector() noexcept : v() {}
    /**
     * @brief 可変長引数によるコンストラクタ
     *
     * 各成分を T に変換して入れる (Vector(1, 2.5) のように型が混ざっても縮小変換の警告を出さない)
     * @tparam Args
     */
    template <typename... Args>
    constexpr Vector(Args... args) noexcept : v{static_cast<T>(args)...} {}

    /**
     * @brief i番目の成分を返す
     *
     * @param i
     * @return T&
     */
    constexpr T& operator[](long long i) noexcept {
        return v[i];
    }
    /**
     * @brief i番目の成分を返す
     *
     * @param i
     * @return T&
     */
    constexpr const T& operator[](long long i) const noexcept {
        return v[i];
    }

    /**
     * @brief 加算代入演算子
     *
     * @param rhs
     * @return Vector&
     */
    constexpr Vector& operator+=(const Vector& rhs) noexcept {
        for (int i = 0; i < Dim; i++) v[i] += rhs[i];
        return *this;
    }
    /**
     * @brief 減算代入演算子
     *
     * @param rhs
     * @return Vector&
     */
    constexpr Vector& operator-=(const Vector& rhs) noexcept {
        for (int i = 0; i < Dim; i++) v[i] -= rhs.v[i];
        return *this;
    }
    /**
     * @brief スカラー倍代入演算子
     *
     * @param coef
     * @return Vector&
     */
    constexpr Vector& operator*=(const T& coef) noexcept {
        for (int i = 0; i < Dim; i++) v[i] *= coef;
        return *this;
    }
    /**
     * @brief スカラーの逆数倍代入演算子
     *
     * @param coef
     * @return Vector&
     */
    constexpr Vector& operator/=(const T& coef) {
        for (int i = 0; i < Dim; i++) {
            if constexpr (std::is_integral_v<T>) {
                assert(v[i] % coef == 0 && "Vector::operator/= : coef must be a divisor of all elements");
            }
            v[i] /= coef;
        }
        return *this;
    }

    /**
     * @brief 単項プラス演算子
     *
     * @return Vector
     */
    [[nodiscard]]
    constexpr Vector operator+() const noexcept {
        return *this;
    }
    /**
     * @brief 単項マイナス演算子
     *
     * @return Vector
     */
    [[nodiscard]]
    constexpr Vector operator-() const noexcept {
        return *this * (-1);
    }

    /**
     * @brief 加算演算子
     *
     * @param lhs
     * @param rhs
     * @return Vector
     */
    [[nodiscard]]
    friend constexpr Vector operator+(const Vector& lhs, const Vector& rhs) noexcept {
        return std::move(Vector(lhs) += rhs);
    }

    /**
     * @brief 減算演算子
     *
     * @param lhs
     * @param rhs
     * @return Vector
     */
    [[nodiscard]]
    friend constexpr Vector operator-(const Vector& lhs, const Vector& rhs) noexcept {
        return std::move(Vector(lhs) -= rhs);
    }

    /**
     * @brief スカラー倍演算子
     *
     * @param lhs
     * @param coef
     * @return Vector
     */
    [[nodiscard]]
    friend constexpr Vector operator*(const Vector& lhs, const T& coef) noexcept {
        return std::move(Vector(lhs) *= coef);
    }

    /**
     * @brief スカラー倍演算子
     *
     * @param coef
     * @param rhs
     * @return Vector
     */
    [[nodiscard]]
    friend constexpr Vector operator*(const T& coef, const Vector& rhs) noexcept {
        return std::move(Vector(rhs) *= coef);
    }

    /**
     * @brief スカラーの逆数倍演算子
     *
     * @param lhs
     * @param coef
     * @return Vector
     */
    [[nodiscard]]
    friend constexpr Vector operator/(const Vector& lhs, const T& coef) {
        return std::move(Vector(lhs) /= coef);
    }

    /**
     * @brief 等価演算子
     *
     * @param lhs
     * @param rhs
     * @return bool
     */
    [[nodiscard]]
    friend constexpr bool operator==(const Vector& lhs, const Vector& rhs) noexcept {
        return lhs.v == rhs.v;
    }

    /**
     * @brief 非等価演算子
     *
     * @param lhs
     * @param rhs
     * @return bool
     */
    [[nodiscard]]
    friend constexpr bool operator!=(const Vector& lhs, const Vector& rhs) noexcept {
        return lhs.v != rhs.v;
    }

    /**
     * @brief 小なり演算子
     *
     * @param lhs
     * @param rhs
     * @return bool
     */
    [[nodiscard]]
    friend constexpr bool operator<(const Vector& lhs, const Vector& rhs) noexcept {
        return lhs.v < rhs.v;
    }
    /**
     * @brief 大なり演算子
     *
     * @param lhs
     * @param rhs
     * @return bool
     */
    [[nodiscard]]
    friend constexpr bool operator>(const Vector& lhs, const Vector& rhs) noexcept {
        return lhs.v > rhs.v;
    }
    /**
     * @brief 小なりイコール演算子
     *
     * @param lhs
     * @param rhs
     * @return bool
     */
    [[nodiscard]]
    friend constexpr bool operator<=(const Vector& lhs, const Vector& rhs) noexcept {
        return lhs.v <= rhs.v;
    }
    /**
     * @brief 大なりイコール演算子
     *
     * @param lhs
     * @param rhs
     * @return bool
     */
    [[nodiscard]]
    friend constexpr bool operator>=(const Vector& lhs, const Vector& rhs) noexcept {
        return lhs.v >= rhs.v;
    }

    /**
     * @brief 入力ストリームからの読み込み
     *
     * @tparam CharT 入力ストリームの文字型
     * @tparam Traits 入力ストリームの文字型特性
     * @param is
     * @param rhs
     * @return std::basic_istream<CharT, Traits>&
     */
    template <class CharT, class Traits>
    friend std::basic_istream<CharT, Traits>& operator>>(std::basic_istream<CharT, Traits>& is, Vector& rhs) {
        for (int i = 0; i < Dim; i++) is >> rhs.v[i];
        return is;
    }
    /**
     * @brief 出力ストリームへの書き込み
     *
     * @tparam CharT 出力ストリームの文字型
     * @tparam Traits 出力ストリームの文字型特性
     * @param is
     * @param rhs
     * @return std::basic_ostream<CharT, Traits>&
     */
    template <class CharT, class Traits>
    friend std::basic_ostream<CharT, Traits>& operator<<(std::basic_ostream<CharT, Traits>& os, const Vector& rhs) {
        for (int i = 0; i < Dim; i++) {
            if (i != 0) os << CharT(' ');
            os << rhs.v[i];
        }
        return os;
    }

    /**
     * @brief 内積
     *
     * @param lhs
     * @param rhs
     * @return T
     */
    friend constexpr T dot(const Vector& lhs, const Vector& rhs) noexcept {
        T ret = 0;
        for (int i = 0; i < Dim; i++) ret += lhs[i] * rhs[i];
        return ret;
    }

    /**
     * @brief 絶対値の2乗
     *
     * @return T
     */
    constexpr T squared_norm() const noexcept {
        return dot(*this, *this);
    }
    /**
     * @brief 絶対値
     *
     * @return double
     */
    constexpr double abs() const noexcept {
        return std::sqrt(squared_norm());
    }
};

/**
 * @brief 成分から作るときの推論ガイド。型は成分の共通の型、次元は成分の個数にする
 *
 * Vector(2LL, 3LL) は Vector<long long, 2>、Vector(1, 2, 3) は Vector<int, 3>、Vector(0.0, 0.0) は Vector<double, 2>
 * (これがないと、テンプレート引数の省略時の値から Vector<double, 2> になってしまう)
 */
template <typename T, typename... U, ENABLE_IF_T(std::is_scalar_v<T> && (std::is_scalar_v<U> && ...))>
Vector(T, U...) -> Vector<std::common_type_t<T, U...>, 1 + sizeof...(U)>;

/**
 * @brief 二次元ベクトルどうしの外積(平行四辺形の符号付き面積)
 *
 * @param lhs
 * @param rhs
 * @tparam T 座標の型
 * @return T
 */
template <typename T>
constexpr T cross(const Vector<T, 2>& lhs, const Vector<T, 2>& rhs) noexcept {
    return lhs[0] * rhs[1] - lhs[1] * rhs[0];
}
/**
 * @brief 三次元ベクトルどうしの外積
 *
 * @param lhs
 * @param rhs
 * @tparam T 座標の型
 * @return Vector<T, 3>
 */
template <typename T>
constexpr Vector<T, 3> cross(const Vector<T, 3>& lhs, const Vector<T, 3>& rhs) noexcept {
    Vector<T, 3> ret;
    ret[0] = lhs[1] * rhs[2] - lhs[2] * rhs[1];
    ret[1] = lhs[2] * rhs[0] - lhs[0] * rhs[2];
    ret[2] = lhs[0] * rhs[1] - lhs[1] * rhs[0];
    return ret;
}

/**
 * @brief 3点の位置関係 (counter-clockwise)
 *
 * 整数型でも使える。浮動小数点型では誤差を考えずに比較する
 *
 * @tparam T 座標の型
 * @return int 1: a→b→c が反時計回り, -1: 時計回り, 2: c, a, b の順に一直線上, -2: a, b, c の順に一直線上, 0: c が線分 ab 上
 */
template <typename T>
constexpr int ccw(const Vector<T, 2>& a, const Vector<T, 2>& b, const Vector<T, 2>& c) {
    Vector<T, 2> u = b - a, v = c - a;
    T cr = cross(u, v);
    if (cr > 0) return 1;
    if (cr < 0) return -1;
    if (dot(u, v) < 0) return 2;
    if (u.squared_norm() < v.squared_norm()) return -2;
    return 0;
}
#line 13 "src/geometry/rectangle.hpp"

/**
 * @brief 半開領域 [left, right) × [bottom, top)。幅・高さ 0 も許す
 * @tparam T 座標の型。省略したら long long
 */
template <typename T = long long>
struct Rectangle {
    T left{}, bottom{}, right{}, top{};

    constexpr Rectangle() = default;
    constexpr Rectangle(T left, T bottom, T right, T top) : left(left), bottom(bottom), right(right), top(top) {
        assert(left <= right && bottom <= top);
    }
    constexpr T width() const { return right - left; }
    constexpr T height() const { return top - bottom; }
    constexpr T area() const { return width() * height(); }
    constexpr bool empty() const { return left == right || bottom == top; }
    /** @brief 左辺・下辺を含み、右辺・上辺を含まない包含判定 */
    constexpr bool contains(T x, T y) const {
        return left <= x && x < right && bottom <= y && y < top;
    }
    constexpr bool contains(const Vector<T, 2>& p) const { return contains(p[0], p[1]); }
    /** @brief 4 辺の座標がすべて等しいか (空の長方形でも座標を比較する) */
    constexpr bool operator==(const Rectangle& other) const {
        return left == other.left && bottom == other.bottom && right == other.right && top == other.top;
    }
    constexpr bool operator!=(const Rectangle& other) const { return !(*this == other); }

    /** @brief left bottom right top の順に読み込む */
    template <class CharT, class Traits>
    friend std::basic_istream<CharT, Traits>& operator>>(std::basic_istream<CharT, Traits>& is, Rectangle& rhs) {
        if (is >> rhs.left >> rhs.bottom >> rhs.right >> rhs.top) {
            assert(rhs.left <= rhs.right && rhs.bottom <= rhs.top);
        }
        return is;
    }
};

template <typename A, typename B, typename C, typename D>
Rectangle(A, B, C, D) -> Rectangle<std::common_type_t<A, B, C, D>>;
#line 2 "src/utility/container_func.hpp"

/**
 * @file container_func.hpp
 * @brief コンテナに対する関数 (sorted, max, sum など)
 */

#include <algorithm>
#line 12 "src/utility/container_func.hpp"
#include <initializer_list>
#line 14 "src/utility/container_func.hpp"
#include <numeric>
#line 17 "src/utility/container_func.hpp"

#line 2 "src/base/functions.hpp"

/**
 * @file functions.hpp
 * @brief 汎用関数 (chmin, chmax など)
 */

#line 11 "src/base/functions.hpp"
#include <limits>
#line 13 "src/base/functions.hpp"
#if __cplusplus >= 202002L
#include <ranges>
#endif
#line 18 "src/base/functions.hpp"

template <typename T1, typename T2>
inline constexpr bool chmin(T1& a, T2 b) {
    if (a > b) {
        a = b;
        return true;
    }
    return false;
}

template <typename T1, typename T2>
inline constexpr bool chmax(T1& a, T2 b) {
    if (a < b) {
        a = b;
        return true;
    }
    return false;
}

inline constexpr long long max(const long long& t1, const long long& t2) {
    return std::max<long long>(t1, t2);
}

inline constexpr long long min(const long long& t1, const long long& t2) {
    return std::min<long long>(t1, t2);
}

using std::abs;
using std::gcd;
using std::lcm;
using std::size;

#if __cplusplus >= 202002L
using std::midpoint;
#else
// C++20 の std::midpoint と同じ (整数は a の側に丸め、あふれない)
template <typename T>
inline constexpr std::enable_if_t<std::is_integral_v<T> && !std::is_same_v<T, bool>, T> midpoint(T a, T b) noexcept {
    using U = std::make_unsigned_t<T>;
    if (a <= b) return static_cast<T>(a + static_cast<T>(static_cast<U>(static_cast<U>(b) - static_cast<U>(a)) >> 1));
    return static_cast<T>(a - static_cast<T>(static_cast<U>(static_cast<U>(a) - static_cast<U>(b)) >> 1));
}
template <typename T>
inline constexpr std::enable_if_t<std::is_floating_point_v<T>, T> midpoint(T a, T b) noexcept {
    constexpr T lo = std::numeric_limits<T>::min() * 2;
    constexpr T hi = std::numeric_limits<T>::max() / 2;
    const T abs_a = a < 0 ? -a : a, abs_b = b < 0 ? -b : b;
    if (abs_a <= hi && abs_b <= hi) return (a + b) / 2;
    if (abs_a < lo) return a + b / 2;
    if (abs_b < lo) return a / 2 + b;
    return a / 2 + b / 2;
}
template <typename T>
inline constexpr std::enable_if_t<std::is_object_v<T>, T*> midpoint(T* a, T* b) noexcept {
    return a + (b - a) / 2;
}
#endif

/**
 * 要素数を long long で返す (std::ssize の long long 版)
 * size() を持つ型なら、begin() と end() を持たない自作の型にも使える
 */
#if __cplusplus >= 202002L
template <typename R>
    requires requires(R& r) { std::ranges::size(r); }
inline constexpr long long len(R&& r) {
    return static_cast<long long>(std::ranges::size(r));
}
#else
template <typename C>
inline constexpr auto len(const C& c) -> decltype(static_cast<long long>(std::size(c))) {
    return static_cast<long long>(std::size(c));
}
#endif

template <typename T>
constexpr T extgcd(const T& a, const T& b, T& x, T& y) {
    T d = a;
    if (b != 0) {
        d = extgcd(b, a % b, y, x);
        y -= (a / b) * x;
    } else {
        x = 1;
        y = 0;
    }
    return d;
}

/**
 * floor(a / b) (b != 0、負の数も可)
 */
template <typename T1, typename T2>
inline constexpr std::common_type_t<T1, T2> floordiv(T1 a, T2 b) {
    return a / b - (a % b != 0 && (a < 0) != (b < 0));
}
/**
 * ceil(a / b) (b != 0、負の数も可)
 */
template <typename T1, typename T2>
inline constexpr std::common_type_t<T1, T2> ceildiv(T1 a, T2 b) {
    return a / b + (a % b != 0 && (a < 0) == (b < 0));
}
/**
 * {floor(a / b), a - b * floor(a / b)} (b != 0、負の数も可)
 * 余りは 0 または b と同じ符号になる
 */
template <typename T1, typename T2>
inline constexpr std::pair<std::common_type_t<T1, T2>, std::common_type_t<T1, T2>> divmod(T1 a, T2 b) {
    std::common_type_t<T1, T2> q = floordiv(a, b);
    return {q, a - q * b};
}

/**
 * 0 <= x < a
 */
inline constexpr bool inrange(long long x, long long a) {
    return 0 <= x && x < a;
}
/**
 * a <= x < b
 */
inline constexpr bool inrange(long long x, long long a, long long b) {
    return a <= x && x < b;
}
/**
 * 0 <= x < a and 0 <= y < b
 */
inline constexpr bool inrect(long long x, long long y, long long a, long long b) {
    return 0 <= x && x < a && 0 <= y && y < b;
}
#line 20 "src/utility/container_func.hpp"

#if __cplusplus >= 202002L
#define METHOD_EXPAND(func)         \
    template <typename T>           \
        requires(has_##func##_v<T>) \
    inline constexpr auto func(const T& t) -> decltype(t.func()) { return t.func(); }

#define METHOD_AND_FUNC_ARG_EXPAND(func)                                                               \
    template <typename T, typename U>                                                                  \
        requires(has_##func##_v<T, U>)                                                                 \
    inline constexpr auto func(const T& t, const U& u) -> decltype(t.func(u)) { return t.func(u); }    \
    template <typename T, typename U>                                                                  \
        requires(!has_##func##_v<T, U>)                                                                \
    inline constexpr auto func(const T& t, const U& u) -> decltype(std::func(t.begin(), t.end(), u)) { \
        if constexpr (requires { std::ranges::func(t, u); }) {                                         \
            return std::ranges::func(t, u);                                                            \
        } else {                                                                                       \
            return std::func(t.begin(), t.end(), u);                                                   \
        }                                                                                              \
    }
#else
#define METHOD_EXPAND(func)                                        \
    template <typename T, ENABLE_IF_T(has_##func##_v<T>)>          \
    inline constexpr auto func(const T& t) -> decltype(t.func()) { \
        return t.func();                                           \
    }

#define METHOD_AND_FUNC_ARG_EXPAND(func)                                  \
    template <typename T, typename U, ENABLE_IF_T(has_##func##_v<T, U>)>  \
    inline constexpr auto func(const T& t, const U& u)                    \
        -> decltype(t.func(u)) {                                          \
        return t.func(u);                                                 \
    }                                                                     \
    template <typename T, typename U, ENABLE_IF_T(!has_##func##_v<T, U>)> \
    inline constexpr auto func(const T& t, const U& u)                    \
        -> decltype(std::func(t.begin(), t.end(), u)) {                   \
        return std::func(t.begin(), t.end(), u);                          \
    }
#endif

METHOD_EXPAND(reversed)
#if __cplusplus >= 202002L
template <class C>
    requires(!has_reversed_v<C>)
#else
template <class C, ENABLE_IF_T(!has_reversed_v<C>)>
#endif
inline constexpr C reversed(C t) {
#if __cplusplus >= 202002L
    if constexpr (requires { std::ranges::reverse(t); }) {
        std::ranges::reverse(t);
    } else
#endif
    {
        std::reverse(t.begin(), t.end());
    }
    return t;
}

namespace internal_container_func {
// comp(proj(a), proj(b)) で比べられるか
#if __cplusplus >= 202002L
template <class C, class F, class P>
concept projected_comp = requires(F& comp, P& proj, const typename C::value_type& value) {
    { std::invoke(comp, std::invoke(proj, value), std::invoke(proj, value)) } -> std::convertible_to<bool>;
};
#else
template <class C, class F, class P, class = void>
struct is_projected_comp : std::false_type {};
template <class C, class F, class P>
struct is_projected_comp<C, F, P, std::void_t<std::invoke_result_t<P&, const mem_value_type<C>&>>>
    : std::is_invocable_r<bool, F&, std::invoke_result_t<P&, const mem_value_type<C>&>, std::invoke_result_t<P&, const mem_value_type<C>&>> {};
#endif
// ranges で扱える iterator では射影を直接渡す。vector<bool> などは従来のアルゴリズムを使う。
template <class C, class F, class P>
constexpr void sort(C& values, F& comp, P& proj) {
#if __cplusplus >= 202002L
    if constexpr (requires { std::ranges::sort(values, std::ref(comp), std::ref(proj)); }) {
        std::ranges::sort(values, std::ref(comp), std::ref(proj));
    } else
#endif
    {
        std::sort(values.begin(), values.end(), [&](const mem_value_type<C>& a, const mem_value_type<C>& b) {
            return std::invoke(comp, std::invoke(proj, a), std::invoke(proj, b));
        });
    }
}
}  // namespace internal_container_func

METHOD_EXPAND(sorted)
#if __cplusplus >= 202002L
template <class C, class F = std::less<>, class P = internal_traits::identity>
    requires(!has_sorted_v<C> && internal_container_func::projected_comp<C, F, P>)
#else
template <class C, class F = std::less<>, class P = internal_traits::identity, ENABLE_IF_T(!has_sorted_v<C> && internal_container_func::is_projected_comp<C, F, P>::value)>
#endif
inline constexpr C sorted(C t, F comp = F(), P proj = P()) {
    internal_container_func::sort(t, comp, proj);
    return t;
}

#if __cplusplus >= 202002L
template <class C, class F = std::less<>, class P = internal_traits::identity>
    requires(internal_container_func::projected_comp<C, F, P>)
#else
template <class C, class F = std::less<>, class P = internal_traits::identity, ENABLE_IF_T(internal_container_func::is_projected_comp<C, F, P>::value)>
#endif
inline constexpr void sort(C& t, F comp = F(), P proj = P()) {
    internal_container_func::sort(t, comp, proj);
}
// sort(c, {}, proj) 用。std::vector などでは ADL で std::sort(first, last, comp) も候補になり、
// {} を F で受けると std::sort が選ばれるので、{} が標準変換で渡る std::nullptr_t で受ける
#if __cplusplus >= 202002L
template <class C, class P>
    requires(internal_container_func::projected_comp<C, std::less<>, P>)
#else
template <class C, class P, ENABLE_IF_T(internal_container_func::is_projected_comp<C, std::less<>, P>::value)>
#endif
inline constexpr void sort(C& t, std::nullptr_t, P proj) {
    sort(t, std::less<>(), proj);
}

template <class C>
inline constexpr void reverse(C& t) {
#if __cplusplus >= 202002L
    if constexpr (requires { std::ranges::reverse(t); }) {
        std::ranges::reverse(t);
    } else
#endif
    {
        std::reverse(t.begin(), t.end());
    }
}

METHOD_EXPAND(max)
#if __cplusplus >= 202002L
template <class C>
    requires(!has_max_v<C> && is_sorted_container_v<C>)
#else
template <class C, ENABLE_IF_T(!has_max_v<C> && is_sorted_container_v<C>)>
#endif
inline constexpr mem_value_type<C> max(const C& v) {
    assert(v.begin() != v.end());
    return *v.rbegin();
}
#if __cplusplus >= 202002L
template <class C>
    requires(!has_max_v<C> && !is_sorted_container_v<C>)
#else
template <class C, ENABLE_IF_T(!has_max_v<C> && !is_sorted_container_v<C>)>
#endif
inline constexpr mem_value_type<C> max(const C& v) {
    assert(v.begin() != v.end());
#if __cplusplus >= 202002L
    if constexpr (requires { std::ranges::max_element(v, std::less<>{}); }) {
        return *std::ranges::max_element(v, std::less<>{});
    } else
#endif
    {
        return *std::max_element(v.begin(), v.end());
    }
}
template <typename T>
inline constexpr T max(const std::initializer_list<T>& v) {
    return std::max(v);
}

METHOD_EXPAND(min)
#if __cplusplus >= 202002L
template <class C>
    requires(!has_min_v<C> && is_sorted_container_v<C>)
#else
template <class C, ENABLE_IF_T(!has_min_v<C> && is_sorted_container_v<C>)>
#endif
inline constexpr mem_value_type<C> min(const C& v) {
    assert(v.begin() != v.end());
    return *v.begin();
}
#if __cplusplus >= 202002L
template <class C>
    requires(!has_min_v<C> && !is_sorted_container_v<C>)
#else
template <class C, ENABLE_IF_T(!has_min_v<C> && !is_sorted_container_v<C>)>
#endif
inline constexpr mem_value_type<C> min(const C& v) {
    assert(v.begin() != v.end());
#if __cplusplus >= 202002L
    if constexpr (requires { std::ranges::min_element(v, std::less<>{}); }) {
        return *std::ranges::min_element(v, std::less<>{});
    } else
#endif
    {
        return *std::min_element(v.begin(), v.end());
    }
}
template <typename T>
inline constexpr T min(const std::initializer_list<T>& v) {
    return std::min(v);
}

METHOD_EXPAND(sum)
#if __cplusplus >= 202002L
template <class C>
    requires(!has_sum_v<C>)
#else
template <class C, ENABLE_IF_T(!has_sum_v<C>)>
#endif
inline constexpr mem_value_type<C> sum(const C& v) {
    return std::accumulate(v.begin(), v.end(), mem_value_type<C>{});
}
template <typename T>
inline constexpr T sum(const std::initializer_list<T>& v) {
    return std::accumulate(v.begin(), v.end(), T{});
}

METHOD_EXPAND(product)
#if __cplusplus >= 202002L
template <class C>
    requires(!has_product_v<C>)
#else
template <class C, ENABLE_IF_T(!has_product_v<C>)>
#endif
inline constexpr mem_value_type<C> product(const C& v) {
    return std::accumulate(v.begin(), v.end(), mem_value_type<C>{1}, std::multiplies<mem_value_type<C>>());
}
template <typename T>
inline constexpr T product(const std::initializer_list<T>& v) {
    return std::accumulate(v.begin(), v.end(), T{1}, std::multiplies<T>());
}

METHOD_EXPAND(product_xor)
#if __cplusplus >= 202002L
template <class C>
    requires(!has_product_xor_v<C>)
#else
template <class C, ENABLE_IF_T(!has_product_xor_v<C>)>
#endif
inline constexpr mem_value_type<C> product_xor(const C& v) {
    return std::accumulate(v.begin(), v.end(), mem_value_type<C>{0}, std::bit_xor<mem_value_type<C>>());
}
template <typename T>
inline constexpr T product_xor(const std::initializer_list<T>& v) {
    return std::accumulate(v.begin(), v.end(), T{0}, std::bit_xor<T>());
}

METHOD_AND_FUNC_ARG_EXPAND(count)
METHOD_AND_FUNC_ARG_EXPAND(find)
METHOD_AND_FUNC_ARG_EXPAND(lower_bound)
METHOD_AND_FUNC_ARG_EXPAND(upper_bound)

template <class C, typename T>
inline constexpr bool contains(const C& c, const T& t) {
    return find(c, t) != c.end();
}

template <class C>
inline constexpr mem_value_type<C> gcd(const C& v) {
    mem_value_type<C> init(0);
    for (const auto& e : v) init = std::gcd(init, e);
    return init;
}

template <class C>
inline constexpr mem_value_type<C> average(const C& v) {
    assert(v.size());
    // v.size() は符号なしなので、そのまま割ると負の和が符号なしに変換されて壊れる
    return sum(v) / static_cast<mem_value_type<C>>(v.size());
}

template <class C>
inline constexpr mem_value_type<C> median(const C& v) {
    assert(!v.empty());
    std::vector<std::size_t> u(v.size());
    std::iota(u.begin(), u.end(), 0);
    std::sort(u.begin(), u.end(), [&](std::size_t a, std::size_t b) {
        return v[a] < v[b];
    });
    if (v.size() & 1) {
        return v[u[v.size() / 2]];
    }
    return midpoint(v[u[v.size() / 2 - 1]], v[u[v.size() / 2]]);
}

// x が最初に現れる位置。なければ -1
template <class C, typename U>
inline constexpr long long index(const C& v, const U& x) {
    auto it = find(v, x);
    if (it == v.end()) return -1;
    return static_cast<long long>(std::distance(v.begin(), it));
}

// f(x) が true になる最初の位置。なければ -1
template <class C, class F>
inline constexpr long long index_if(const C& v, F f) {
    long long i = 0;
    for (const auto& e : v) {
        if (f(e)) return i;
        i++;
    }
    return -1;
}

// f(x) が true になる位置を昇順に並べたもの
template <class C, class F>
inline std::vector<long long> indices_if(const C& v, F f) {
    std::vector<long long> res;
    long long i = 0;
    for (const auto& e : v) {
        if (f(e)) res.push_back(i);
        i++;
    }
    return res;
}

// f(x) が true になる要素の個数
template <class C, class F>
inline constexpr long long count_if(const C& v, F f) {
    long long res = 0;
    for (const auto& e : v) {
        if (f(e)) res++;
    }
    return res;
}

/**
 * @brief 同じ長さの 2 つの列のハミング距離 (要素が異なる位置の数) O(N)
 *
 * @tparam R1 配列の型
 * @tparam R2 配列の型
 * @param s 配列
 * @param t 配列 (s と同じ長さ)
 * @return long long ハミング距離
 */
template <typename R1, typename R2>
inline constexpr auto hamming_distance(const R1& s, const R2& t) -> decltype(std::begin(s), std::begin(t), 0LL) {
    auto a = std::begin(s);
    auto b = std::begin(t);
    long long n = std::end(s) - a;
    assert(n == std::end(t) - b);
    long long res = 0;
    for (long long i = 0; i < n; i++) {
        if (!(a[i] == b[i])) res++;
    }
    return res;
}

#if __cplusplus >= 202002L
template <class C>
    requires(std::integral<mem_value_type<C>>)
#else
template <class C, ENABLE_IF_T(std::is_integral_v<mem_value_type<C>>)>
#endif
inline constexpr mem_value_type<C> mex(const C& v) {
    std::vector<bool> b(v.size() + 1);
    for (const auto& a : v) {
        if (0 <= a && static_cast<std::size_t>(a) < b.size()) {
            b[a] = true;
        }
    }
    mem_value_type<C> ret = 0;  // b の要素数は v より 1 多いので、下のループで必ず見つかる
    for (std::size_t i = 0; i < b.size(); i++) {
        if (!b[i]) {
            ret = i;
            break;
        }
    }
    return ret;
}

template <class C>
inline constexpr long long bisect_left(const C& v, const mem_value_type<C>& x) {
    return static_cast<long long>(std::distance(v.begin(), lower_bound(v, x)));
}
template <class C>
inline constexpr long long bisect_right(const C& v, const mem_value_type<C>& x) {
    return static_cast<long long>(std::distance(v.begin(), upper_bound(v, x)));
}
#line 2 "src/utility/range.hpp"

/**
 * @file range.hpp
 * @brief Python の range のような整数列と、その直積の Grid
 */

#line 11 "src/utility/range.hpp"
#include <string>
#line 15 "src/utility/range.hpp"

struct Range {
   public:
    using value_type = long long;
    using const_reference = value_type;
    using size_type = long long;
    using difference_type = std::ptrdiff_t;

    const value_type start;
    const value_type stop;
    const value_type step;

   private:
    const value_type norm_stop;

    constexpr static value_type normalize(value_type _start, value_type _stop, value_type _step) {
        assert(_step != 0);
        if (_step > 0) {
            if (_start >= _stop) {
                return _start;
            } else {
                return _start + (_stop - _start + _step - 1) / _step * _step;
            }
        } else {
            if (_start <= _stop) {
                return _start;
            } else {
                return _start - (_start - _stop - _step - 1) / _step * _step;
            }
        }
    }

    constexpr Range(value_type _start, value_type _stop, value_type _step, value_type _norm_stop)
        : start(_start), stop(_stop), step(_step), norm_stop(_norm_stop) {
    }

   public:
    /**
     * @brief start から stop の手前まで step ずつ進む整数列
     * @pre step != 0
     */
    constexpr Range(value_type _start, value_type _stop, value_type _step)
        : start(_start), stop(_stop), step(_step), norm_stop(normalize(_start, _stop, _step)) {
    }
    constexpr Range(value_type _start, value_type _stop)
        : start(_start), stop(_stop), step(1), norm_stop(normalize(_start, _stop, 1)) {}
    explicit constexpr Range(value_type _stop)
        : start(0), stop(_stop), step(1), norm_stop(normalize(0, _stop, 1)) {}
    constexpr Range()
        : start(0), stop(0), step(1), norm_stop(0) {
    }
    constexpr Range(const Range& o) = default;
    Range& operator=(const Range& o) = delete;

    struct const_iterator {
       public:
        using difference_type = Range::difference_type;
        using value_type = Range::value_type;
        using pointer = void;
        using reference = Range::const_reference;
        using iterator_category = std::random_access_iterator_tag;

       private:
        value_type first = 0, stop = 0, step = 1, value = 0;

        constexpr bool same_range(const const_iterator& o) const noexcept {
            return first == o.first && stop == o.stop && step == o.step;
        }

       public:
        constexpr const_iterator() noexcept = default;
        constexpr const_iterator(const Range& range, value_type value) noexcept
            : first(range.start), stop(range.stop), step(range.step), value(value) {}
        constexpr reference base() const noexcept {
            return value;
        }
        constexpr const_iterator& operator++() noexcept {
            value += step;
            return *this;
        }
        constexpr const_iterator operator++(int) noexcept {
            const_iterator ret(*this);
            value += step;
            return ret;
        }
        constexpr const_iterator& operator+=(difference_type _n) noexcept {
            value += _n * step;
            return *this;
        }
        constexpr friend const_iterator operator+(const const_iterator& i, difference_type _n) noexcept {
            const_iterator ret(i);
            ret += _n;
            return ret;
        }
        constexpr friend const_iterator operator+(difference_type _n, const const_iterator& i) noexcept {
            const_iterator ret(i);
            ret += _n;
            return ret;
        }
        constexpr const_iterator& operator--() noexcept {
            value -= step;
            return *this;
        }
        constexpr const_iterator operator--(int) noexcept {
            const_iterator ret(*this);
            value -= step;
            return ret;
        }
        constexpr const_iterator& operator-=(difference_type _n) noexcept {
            value -= _n * step;
            return *this;
        }
        constexpr friend const_iterator operator-(const const_iterator& i, difference_type _n) noexcept {
            const_iterator ret(i);
            ret -= _n;
            return ret;
        }
        constexpr reference operator[](difference_type i) const noexcept { return value + i * step; }
        constexpr reference operator*() const noexcept {
            return value;
        }
        constexpr friend bool operator!=(const const_iterator& a, const const_iterator& b) noexcept {
            return !a.same_range(b) || a.value != b.value;
        }
        constexpr friend bool operator==(const const_iterator& a, const const_iterator& b) noexcept {
            return !(a != b);
        }
        constexpr friend bool operator<(const const_iterator& a, const const_iterator& b) noexcept {
            assert(a.same_range(b));
            return a.step > 0 ? a.value < b.value : a.value > b.value;
        }
        constexpr friend bool operator>(const const_iterator& a, const const_iterator& b) noexcept { return b < a; }
        constexpr friend bool operator<=(const const_iterator& a, const const_iterator& b) noexcept { return !(b < a); }
        constexpr friend bool operator>=(const const_iterator& a, const const_iterator& b) noexcept { return !(a < b); }
        constexpr friend difference_type operator-(const const_iterator& a, const const_iterator& b) {
            assert(a.same_range(b));
            if (a.step > 0) {
                return (a.value - b.value) / a.step;
            } else {
                return (b.value - a.value) / (-a.step);
            }
        }
    };

    constexpr const_iterator begin() const noexcept {
        return {*this, start};
    }
    constexpr const_iterator end() const noexcept {
        return {*this, norm_stop};
    }
    /**
     * @brief x の個数 (0 か 1)
     */
    constexpr size_type count(value_type x) const noexcept {
        // step がコンパイル時に分からないときも、よく使う step = 1 では割り算をしない
        if (step == 1) return start <= x && x < stop;
        if (step > 0) {
            if (start <= x && x < stop) {
                if ((x - start) % step == 0) {
                    return 1;
                }
            }
        } else {
            if (stop < x && x <= start) {
                if ((start - x) % (-step) == 0) {
                    return 1;
                }
            }
        }
        return 0;
    }
    /**
     * @brief x が含まれるか
     */
    constexpr bool contains(value_type x) const noexcept {
        return count(x) != 0;
    }
    /**
     * @brief x のインデックス
     * x が含まれないとエラー
     */
    constexpr size_type index(value_type x) const {
        assert(contains(x));
        if (step == 1) return x - start;
        return (x - start) / step;
    }
    /**
     * @brief 要素が x のイテレータ
     * x が含まれないと end() を返す
     */
    constexpr const_iterator find(value_type x) const noexcept {
        if (contains(x)) {
            return {*this, x};
        } else {
            return {*this, norm_stop};
        }
    }
    /**
     * @brief 要素が x 以上の最小のイテレータ
     * step > 0 じゃないとエラー
     */
    constexpr const_iterator lower_bound(value_type x) const {
        assert(step > 0);
        if (norm_stop <= x) {
            return end();
        } else if (x < start) {
            return begin();
        } else {
            return {*this, start + (x - start + step - 1) / step * step};
        }
    }
    /**
     * @brief 要素が x より大きい最小のイテレータ
     * step > 0 じゃないとエラー
     */
    constexpr const_iterator upper_bound(value_type x) const {
        assert(step > 0);
        if (norm_stop <= x) {
            return end();
        } else if (x < start) {
            return begin();
        } else {
            return {*this, start + (x - start + step) / step * step};
        }
    }
    /**
     * @brief コンテナの要素数
     */
    constexpr size_type size() const noexcept {
        if (step > 0) {
            return (norm_stop - start) / step;
        } else {
            return (start - norm_stop) / (-step);
        }
    }
    constexpr value_type at(size_type i) const {
        assert(0 <= i && i < size());
        return start + i * step;
    }
    constexpr value_type operator[](size_type i) const {
        return at(i);
    }
    constexpr bool empty() const noexcept {
        return start == norm_stop;
    }
    constexpr value_type sum() const noexcept {
        return size() * (norm_stop - step + start) / 2;
    }
    /**
     * @brief 最小値
     * 空だとエラー
     */
    constexpr value_type min() const {
        assert(!empty());
        if (step > 0) {
            return start;
        } else {
            return norm_stop - step;
        }
    }
    /**
     * @brief 最大値
     * 空だとエラー
     */
    constexpr value_type max() const {
        assert(!empty());
        if (step > 0) {
            return norm_stop - step;
        } else {
            return start;
        }
    }
    /**
     * @brief 総 xor
     * 負を含むとエラー
     */
    constexpr value_type product_xor() const noexcept {
        if (empty()) return 0;
        assert(min() >= 0);
        Range sorted_range(sorted());
        value_type res = 0;
        std::make_unsigned_t<value_type> t = 1;
        while (t <= static_cast<std::make_unsigned_t<value_type>>(max())) {
            std::make_unsigned_t<value_type> tmp = 0, n = size(), m = t, a = sorted_range.step, b = sorted_range.start;
            while (true) {
                if (a >= m) {
                    tmp += n * (n - 1) / 2 * (a / m);
                    a %= m;
                }
                if (b >= m) {
                    tmp += n * (b / m);
                    b %= m;
                }
                std::make_unsigned_t<value_type> y_max = a * n + b;
                if (y_max < m) break;
                n = y_max / m;
                b = y_max % m;
                std::swap(m, a);
            }
            if (tmp % 2 == 1) {
                res += t;
            }
            t <<= 1;
        }
        return res;
    }
    /**
     * @brief 逆順にしたもの
     */
    constexpr Range reversed() const noexcept {
        return {norm_stop - step, start - step, -step, start - step};
    }
    /**
     * @brief step > 0 だとそのまま step < 0 だと逆順にしたもの
     */
    constexpr Range sorted() const noexcept {
        if (step > 0) {
            return {start, norm_stop, step, norm_stop};
        } else {
            return {norm_stop - step, start - step, -step, start - step};
        }
    }
    /**
     * @brief 要素が [l, r) である範囲を返す
     */
    constexpr Range clipped(value_type l, value_type r) const {
        if (l >= r) return {};
        r--;  // 以下では r を含む [l, r] として扱う
        if (step > 0) {
            value_type _start = [&] {
                if (norm_stop <= l) {
                    return norm_stop;
                } else if (l < start) {
                    return start;
                } else {
                    return start + (l - start + step - 1) / step * step;
                }
            }();
            value_type _stop = [&] {
                if (norm_stop <= r) {
                    return norm_stop;
                } else if (r < start) {
                    return start;
                } else {
                    return start + (r - start + step) / step * step;
                }
            }();
            return {_start, _stop, step, _stop};
        } else {
            value_type _start = [&] {
                if (start - step <= r) {
                    return start;
                } else if (r < norm_stop - step) {
                    return norm_stop;
                } else {
                    return norm_stop + (r - norm_stop) / step * step;
                }
            }();
            value_type _stop = [&] {
                if (start - step <= l) {
                    return start;
                } else if (l < norm_stop - step) {
                    return norm_stop;
                } else {
                    return norm_stop + (l - norm_stop - 1) / step * step;
                }
            }();
            return {_start, _stop, step, _stop};
        }
    }
    /**
     * @brief 要素を Range で指定したコンテナ
     */
    constexpr Range slice(const Range& r) const {
        if (r.empty()) return {};
        if (r.max() < 0) return {};
        if (r.min() >= size()) return {};
        Range trimmed_range(r.clipped(0, size()));
        if (trimmed_range.empty()) return {};
        value_type _step = step * trimmed_range.step;
        value_type _start = at(trimmed_range.start);
        value_type _stop = _start + _step * trimmed_range.size();
        return {_start, _stop, _step, _stop};
    }

    static std::string type_str() {
        return "Range";
    }
    std::string initializer_str() const {
        return "{" + std::to_string(start) + ", " + std::to_string(stop) + ", " + std::to_string(step) + "}";
    }
    std::string repr() const {
        return "Range(" + std::to_string(start) + ", " + std::to_string(stop) + ", " + std::to_string(step) + ")";
    }

    std::vector<value_type> to_vector() const {
        std::vector<value_type> ret;
        ret.reserve(size());
        if (step > 0) {
            for (value_type x = start; x < stop; x += step) {
                ret.push_back(x);
            }
        } else {
            for (value_type x = start; x > stop; x += step) {
                ret.push_back(x);
            }
        }
        return ret;
    }
    constexpr friend bool operator==(const Range& a, const Range& b) noexcept {
        if (a.empty() && b.empty()) return true;
        if (a.size() != b.size()) return false;
        if (a.start != b.start) return false;
        if (a.size() == 1) return true;
        if (a.step != b.step) return false;
        return true;
    }
    constexpr friend bool operator!=(const Range& a, const Range& b) noexcept {
        return !(a == b);
    }
};

/**
 * @brief 2 つの Range の直積 rows × cols
 * (i, j) を i の昇順、同じ i では j の昇順 (行優先) に並べたものとして扱う
 */
struct Grid {
   public:
    using value_type = std::pair<long long, long long>;
    using size_type = long long;
    using difference_type = std::ptrdiff_t;

    const Range rows;
    const Range cols;

   private:
    const long long width;  // cols.size() (index や at で毎回割り算しないように持っておく)

   public:
    /**
     * @brief [0, h) × [0, w)
     */
    constexpr Grid(long long h, long long w) : rows(h), cols(w), width(cols.size()) {}
    constexpr Grid(const Range& _rows, const Range& _cols) : rows(_rows), cols(_cols), width(cols.size()) {}
    constexpr Grid(const Grid& o) = default;
    Grid& operator=(const Grid& o) = delete;

    struct const_iterator {
       public:
        using difference_type = Grid::difference_type;
        using value_type = Grid::value_type;
        using pointer = void;
        using reference = value_type;
        using iterator_category = std::forward_iterator_tag;

       private:
        const Grid* rect = nullptr;
        long long w = 0;   // cols.size()
        long long ic = 0;  // rows の何番目か
        long long jc = 0;  // cols の何番目か

       public:
        constexpr const_iterator() noexcept = default;
        constexpr const_iterator(const Grid* _rect, long long _w, long long _ic, long long _jc) noexcept
            : rect(_rect), w(_w), ic(_ic), jc(_jc) {}
        constexpr value_type operator*() const noexcept {
            return {rect->rows.start + ic * rect->rows.step, rect->cols.start + jc * rect->cols.step};
        }
        constexpr const_iterator& operator++() noexcept {
            if (++jc == w) {
                jc = 0;
                ++ic;
            }
            return *this;
        }
        constexpr const_iterator operator++(int) noexcept {
            const_iterator ret(*this);
            ++*this;
            return ret;
        }
        constexpr friend bool operator==(const const_iterator& a, const const_iterator& b) noexcept {
            return a.ic == b.ic && a.jc == b.jc;
        }
        constexpr friend bool operator!=(const const_iterator& a, const const_iterator& b) noexcept {
            return !(a == b);
        }
    };

    constexpr const_iterator begin() const noexcept {
        return {this, width, width == 0 ? rows.size() : 0, 0};
    }
    constexpr const_iterator end() const noexcept {
        return {this, width, rows.size(), 0};
    }
    /**
     * @brief 要素数 rows.size() * cols.size()
     */
    constexpr size_type size() const noexcept {
        return rows.size() * width;
    }
    constexpr bool empty() const noexcept {
        return rows.empty() || cols.empty();
    }
    /**
     * @brief (i, j) が含まれるか
     */
    constexpr bool contains(long long i, long long j) const noexcept {
        return rows.contains(i) && cols.contains(j);
    }
    constexpr bool contains(const value_type& p) const noexcept {
        return contains(p.first, p.second);
    }
    /**
     * @brief (i, j) の行優先での位置 (グリッドの頂点番号に使う)
     * (i, j) が含まれないとエラー
     */
    constexpr size_type index(long long i, long long j) const {
        assert(contains(i, j));
        return rows.index(i) * width + cols.index(j);
    }
    constexpr size_type index(const value_type& p) const {
        return index(p.first, p.second);
    }
    /**
     * @brief 行優先で k 番目の要素 (index の逆)
     */
    constexpr value_type at(size_type k) const {
        assert(0 <= k && k < size());
        return {rows[k / width], cols[k % width]};
    }
    constexpr value_type operator[](size_type k) const {
        return at(k);
    }

   private:
    // 近傍の方向 (rows・cols の中での位置の差) を Grid の順に並べたもの。先頭 4 つは上下左右だけを並べた別の表
    // 4 近傍と 8 近傍の境目が分かるように 2 行に分けているので整形しない
    // clang-format off
    static constexpr int neighbor_dirs[12][2] = {{-1, 0}, {0, -1}, {0, 1}, {1, 0},
                                                 {-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}};
    // clang-format on

   public:
    /**
     * @brief neighbors4 / neighbors8 の戻り値 (範囲 for で使う)
     * 作るときに Grid に含まれる方向をビットで持っておき、立っているビットを順に返す
     */
    struct Neighbors {
        long long i, j, row_step, col_step;
        int first;      // neighbor_dirs[first + k] がビット k の方向
        unsigned mask;  // Grid に含まれる方向

        struct iterator {
            using difference_type = std::ptrdiff_t;
            using value_type = Grid::value_type;
            using pointer = void;
            using reference = value_type;
            using iterator_category = std::forward_iterator_tag;

            const Neighbors* nb = nullptr;
            unsigned rest = 0;  // まだ返していない方向

            constexpr value_type operator*() const noexcept {
                const int k = nb->first + __builtin_ctz(rest);
                return {nb->i + neighbor_dirs[k][0] * nb->row_step, nb->j + neighbor_dirs[k][1] * nb->col_step};
            }
            constexpr iterator& operator++() noexcept {
                rest &= rest - 1;
                return *this;
            }
            constexpr iterator operator++(int) noexcept {
                iterator ret(*this);
                ++*this;
                return ret;
            }
            constexpr friend bool operator==(const iterator& a, const iterator& b) noexcept { return a.rest == b.rest; }
            constexpr friend bool operator!=(const iterator& a, const iterator& b) noexcept { return a.rest != b.rest; }
        };
        constexpr iterator begin() const noexcept { return {this, mask}; }
        constexpr iterator end() const noexcept { return {this, 0}; }
        constexpr long long size() const noexcept { return __builtin_popcount(mask); }
        constexpr bool empty() const noexcept { return mask == 0; }
    };

   private:
    constexpr Neighbors neighbors(long long i, long long j, int first, int last) const {
        assert(contains(i, j));
        unsigned mask = 0;
        for (int k = first; k < last; k++) {
            if (contains(i + neighbor_dirs[k][0] * rows.step, j + neighbor_dirs[k][1] * cols.step)) mask |= 1u << (k - first);
        }
        return {i, j, rows.step, cols.step, first, mask};
    }

   public:
    /**
     * @brief (i, j) の上下左右のうち Grid に含まれるものを、Grid の順に返す
     * 隣は rows・cols の中で隣り合う要素 (i ± rows.step など)。(i, j) が含まれないとエラー
     */
    constexpr Neighbors neighbors4(long long i, long long j) const {
        return neighbors(i, j, 0, 4);
    }
    constexpr Neighbors neighbors4(const value_type& p) const {
        return neighbors4(p.first, p.second);
    }
    /**
     * @brief (i, j) を囲む 8 つのうち Grid に含まれるものを、Grid の順に返す
     */
    constexpr Neighbors neighbors8(long long i, long long j) const {
        return neighbors(i, j, 4, 12);
    }
    constexpr Neighbors neighbors8(const value_type& p) const {
        return neighbors8(p.first, p.second);
    }

    static std::string type_str() {
        return "Grid";
    }
    std::string initializer_str() const {
        return "{" + rows.initializer_str() + ", " + cols.initializer_str() + "}";
    }
    std::string repr() const {
        return "Grid(" + rows.repr() + ", " + cols.repr() + ")";
    }

    constexpr friend bool operator==(const Grid& a, const Grid& b) noexcept {
        if (a.empty() && b.empty()) return true;
        return a.rows == b.rows && a.cols == b.cols;
    }
    constexpr friend bool operator!=(const Grid& a, const Grid& b) noexcept {
        return !(a == b);
    }
};
#line 2 "src/utility/vector_func.hpp"

/**
 * @file vector_func.hpp
 * @brief vector に対する演算子と関数
 */

#line 16 "src/utility/vector_func.hpp"

#line 18 "src/utility/vector_func.hpp"

/**
 * @brief 値を proj で写して comp の順に安定ソートしたときの添字の並び (APL の grade up)
 */
template <typename T, typename F = std::less<>, typename P = internal_traits::identity>
std::vector<long long> argsort(const std::vector<T>& v, F comp = F(), P proj = P()) {
    std::vector<long long> ret(v.size());
    std::iota(ret.begin(), ret.end(), 0LL);
    std::stable_sort(ret.begin(), ret.end(), [&](long long i, long long j) {
        return std::invoke(comp, std::invoke(proj, v[i]), std::invoke(proj, v[j]));
    });
    return ret;
}

/**
 * @brief 各要素の順位 (proj で写して comp の順で v[i] より前に来る要素の個数)。同率は同じ順位で、次の順位は飛ばす
 */
template <typename T, typename F = std::less<>, typename P = internal_traits::identity>
std::vector<long long> rank(const std::vector<T>& v, F comp = F(), P proj = P()) {
    const long long n = v.size();
    std::vector<long long> p = argsort(v, comp, proj), ret(n);
    for (long long i = 0; i < n; i++) {
        ret[p[i]] = i > 0 && !std::invoke(comp, std::invoke(proj, v[p[i - 1]]), std::invoke(proj, v[p[i]])) ? ret[p[i - 1]] : i;
    }
    return ret;
}

/**
 * @brief 逆置換 (ret[p[i]] = i)。p は 0, ..., n-1 の置換であること
 */
#if __cplusplus >= 202002L
template <typename I>
    requires(std::integral<I>)
#else
template <typename I, ENABLE_IF_T(std::is_integral_v<I>)>
#endif
std::vector<long long> inverse_permutation(const std::vector<I>& p) {
    const long long n = p.size();
    std::vector<long long> ret(n, -1);
    for (long long i = 0; i < n; i++) {
        const long long x = static_cast<long long>(p[i]);
        assert(0 <= x && x < n && ret[x] == -1);
        ret[x] = i;
    }
    return ret;
}

/**
 * @brief {v[idx[0]], v[idx[1]], ...} (Uiua の select)
 */
#if __cplusplus >= 202002L
template <typename T, typename I>
    requires(std::integral<I>)
#else
template <typename T, typename I, ENABLE_IF_T(std::is_integral_v<I>)>
#endif
std::vector<T> select(const std::vector<T>& v, const std::vector<I>& idx) {
    std::vector<T> ret;
    ret.reserve(idx.size());
    for (I i : idx) {
        assert(0 <= static_cast<long long>(i) && static_cast<long long>(i) < static_cast<long long>(v.size()));
        ret.push_back(v[i]);
    }
    return ret;
}

template <typename T>
inline std::vector<T>& operator++(std::vector<T>& v) {
    for (auto& e : v) e++;
    return v;
}
template <typename T>
inline std::vector<T> operator++(std::vector<T>& v, int) {
    auto res = v;
    for (auto& e : v) e++;
    return res;
}
template <typename T>
inline std::vector<T>& operator--(std::vector<T>& v) {
    for (auto& e : v) e--;
    return v;
}
template <typename T>
inline std::vector<T> operator--(std::vector<T>& v, int) {
    auto res = v;
    for (auto& e : v) e--;
    return res;
}

#if __cplusplus >= 202002L
template <typename T, typename U>
    requires(std::convertible_to<U, T>)
#else
template <typename T, typename U, ENABLE_IF_T(std::is_convertible_v<U, T>)>
#endif
inline std::vector<T>& operator+=(std::vector<T>& v1, const std::vector<U>& v2) {
    if (v2.size() > v1.size()) {
        v1.resize(v2.size());
    }
    for (std::size_t i = 0; i < v2.size(); i++) {
        v1[i] += v2[i];
    }
    return v1;
}

#if __cplusplus >= 202002L
template <typename T, typename U>
    requires(std::convertible_to<U, T>)
#else
template <typename T, typename U, ENABLE_IF_T(std::is_convertible_v<U, T>)>
#endif
inline std::vector<T> operator+(const std::vector<T>& v1, const std::vector<U>& v2) {
    std::vector<T> res(v1);
    return res += v2;
}

#if __cplusplus >= 202002L
template <typename T, typename U>
    requires(std::convertible_to<U, T>)
#else
template <typename T, typename U, ENABLE_IF_T(std::is_convertible_v<U, T>)>
#endif
inline std::vector<T>& operator+=(std::vector<T>& v, const U& u) {
    for (T& e : v) {
        e += u;
    }
    return v;
}

#if __cplusplus >= 202002L
template <typename T, typename U>
    requires(std::convertible_to<U, T>)
#else
template <typename T, typename U, ENABLE_IF_T(std::is_convertible_v<U, T>)>
#endif
inline std::vector<T> operator+(const std::vector<T>& v, const U& u) {
    std::vector<T> res(v);
    return res += u;
}

#if __cplusplus >= 202002L
template <typename T, typename U>
    requires(std::convertible_to<U, T>)
#else
template <typename T, typename U, ENABLE_IF_T(std::is_convertible_v<U, T>)>
#endif
inline std::vector<T> operator+(const U& u, const std::vector<T>& v) {
    std::vector<T> res(v);
    return res += u;
}

#if __cplusplus >= 202002L
template <typename T, typename U>
    requires(std::convertible_to<U, T>)
#else
template <typename T, typename U, ENABLE_IF_T(std::is_convertible_v<U, T>)>
#endif
inline std::vector<T>& operator*=(std::vector<T>& v1, const std::vector<U>& v2) {
    if (v2.size() > v1.size()) {
        v1.resize(v2.size());
    }
    for (std::size_t i = 0; i < v2.size(); i++) {
        v1[i] *= v2[i];
    }
    for (std::size_t i = v2.size(); i < v1.size(); i++) {
        v1[i] *= U(0);
    }
    return v1;
}

#if __cplusplus >= 202002L
template <typename T, typename U>
    requires(std::convertible_to<U, T>)
#else
template <typename T, typename U, ENABLE_IF_T(std::is_convertible_v<U, T>)>
#endif
inline std::vector<T> operator*(const std::vector<T>& v1, const std::vector<U>& v2) {
    std::vector<T> res(v1);
    return res *= v2;
}

#if __cplusplus >= 202002L
template <typename T, typename U>
    requires(std::convertible_to<U, T>)
#else
template <typename T, typename U, ENABLE_IF_T(std::is_convertible_v<U, T>)>
#endif
inline std::vector<T>& operator*=(std::vector<T>& v, const U& u) {
    for (T& e : v) {
        e *= u;
    }
    return v;
}

#if __cplusplus >= 202002L
template <typename T, typename U>
    requires(std::convertible_to<U, T>)
#else
template <typename T, typename U, ENABLE_IF_T(std::is_convertible_v<U, T>)>
#endif
inline std::vector<T> operator*(const std::vector<T>& v, const U& u) {
    std::vector<T> res(v);
    return res *= u;
}

#if __cplusplus >= 202002L
template <typename T, typename U>
    requires(std::convertible_to<U, T>)
#else
template <typename T, typename U, ENABLE_IF_T(std::is_convertible_v<U, T>)>
#endif
inline std::vector<T> operator*(const U& u, const std::vector<T>& v) {
    std::vector<T> res(v);
    return res *= u;
}

template <typename T, typename U>
inline std::vector<T>& assign(std::vector<T>& v1, const std::vector<U>& v2) {
    v1.assign(v2.begin(), v2.end());
    return v1;
}

template <typename T, typename U>
inline std::vector<T>& extend(std::vector<T>& v1, const std::vector<U>& v2) {
    v1.insert(v1.end(), v2.begin(), v2.end());
    return v1;
}

#if __cplusplus >= 202002L
template <typename T, typename U>
    requires(std::convertible_to<U, T>)
#else
template <typename T, typename U, ENABLE_IF_T(std::is_convertible_v<U, T>)>
#endif
inline std::vector<T>& operator|=(std::vector<T>& v1, const std::vector<U>& v2) {
    return extend(v1, v2);
}

#if __cplusplus >= 202002L
template <typename T, typename U>
    requires(std::integral<U>)
#else
template <typename T, typename U, ENABLE_IF_T(std::is_integral_v<U>)>
#endif
inline std::vector<T>& operator|=(std::vector<T>& v, const U& u) {
    if constexpr (std::is_signed_v<U>) assert(u >= 0);
    std::vector<T> w(v);
    v.clear();
    for (long long i = 0; i < static_cast<long long>(u); i++) {
        extend(v, w);
    }
    return v;
}

#if __cplusplus >= 202002L
template <typename T, typename U>
    requires(std::integral<U>)
#else
template <typename T, typename U, ENABLE_IF_T(std::is_integral_v<U>)>
#endif
inline std::vector<T> operator|(const std::vector<T>& v, const U& u) {
    std::vector<T> res(v);
    return res |= u;
}

#if __cplusplus >= 202002L
template <typename T, typename U>
    requires(std::integral<U>)
#else
template <typename T, typename U, ENABLE_IF_T(std::is_integral_v<U>)>
#endif
inline std::vector<T> operator|(const U& u, const std::vector<T>& v) {
    std::vector<T> res(v);
    return res |= u;
}

template <typename T>
inline std::vector<T> abs(const std::vector<T>& v) {
    std::vector<T> ret;
    ret.reserve(v.size());
    for (const T& e : v) ret.push_back(std::abs(e));
    return ret;
}

template <typename T>
std::vector<T> cumulative_sum(std::vector<T> v) {
    v.insert(v.begin(), T{});
    std::vector<T> ret(v.size());
    std::partial_sum(v.begin(), v.end(), ret.begin());
    return ret;
}

#if __cplusplus >= 202002L
template <typename T>
    requires(std::integral<T>)
#else
template <typename T, ENABLE_IF_T(std::is_integral_v<T>)>
#endif
std::vector<T> iota(T n) {
    assert(n >= 0);
    std::vector<T> ret(n);
    std::iota(ret.begin(), ret.end(), 0);
    return ret;
}

template <typename T>
std::vector<T> unique(const std::vector<T>& v) {
    std::vector<T> res(v);
    std::sort(res.begin(), res.end());
    res.erase(std::unique(res.begin(), res.end()), res.end());
    return res;
}

inline long long radix_convert(const std::vector<long long>& v, int base = 10) {
    assert(base >= 2);
    long long res = 0;
    for (long long d : v) {
        assert(0 <= d && d < base);
        res = res * base + d;
    }
    return res;
}

inline std::vector<long long> radix_convert(long long v, int base = 10) {
    assert(v >= 0 && base >= 2);
    std::vector<long long> res;
    while (v > 0) {
        res.push_back(v % base);
        v /= base;
    }
    std::reverse(res.begin(), res.end());
    return res;
}
#line 10 "test/aoj/dsl/dsl-4-a.1.test.cpp"

int main() {
    int n;
    std::cin >> n;
    std::vector<Rectangle<long long>> rects(n);
    std::vector<long long> xs, ys;
    for (int i = 0; i < n; i++) {
        std::cin >> rects[i];
        xs.push_back(rects[i].left), xs.push_back(rects[i].right);
        ys.push_back(rects[i].bottom), ys.push_back(rects[i].top);
    }
    // 座標圧縮
    xs = unique(xs);
    ys = unique(ys);
    int w = xs.size(), h = ys.size();
    std::vector<std::vector<int>> imos(w, std::vector<int>(h));
    for (int i = 0; i < n; i++) {
        int a = bisect_left(xs, rects[i].left), b = bisect_left(xs, rects[i].right);
        int c = bisect_left(ys, rects[i].bottom), d = bisect_left(ys, rects[i].top);
        imos[a][c]++, imos[a][d]--, imos[b][c]--, imos[b][d]++;
    }
    for (auto [i, j] : Grid(Range(w), Range(1, h))) imos[i][j] += imos[i][j - 1];
    for (auto [i, j] : Grid(Range(1, w), Range(h))) imos[i][j] += imos[i - 1][j];
    long long ans = 0;
    for (auto [i, j] : Grid(w - 1, h - 1)) {
        if (imos[i][j] > 0) ans += (xs[i + 1] - xs[i]) * (ys[j + 1] - ys[j]);
    }
    std::cout << ans << '\n';
}
Back to top page