shogo-library

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

View the Project on GitHub shogo314/shogo-library

:heavy_check_mark: コンテナに対する関数 (sorted, max, sum など)
(src/utility/container_func.hpp)

コンテナ全体を受け取る Python 風の関数です。begin()、end() を持つコンテナならたいてい使えます。

コンテナが同名のメンバ関数を持つ場合は、そちらを呼びます。そのときの計算量はメンバ関数の計算量になります (Range の sum は $O(1)$ など)。find、count、lower_bound、upper_bound は std::set などではメンバ関数を、それ以外では std:: のアルゴリズムを使います。

std::vector<int> v = {3, 1, 4, 1, 5};
auto w = sorted(v);            // {1, 1, 3, 4, 5}
int s = sum(v), mx = max(v);   // 14, 5
long long i = bisect_left(w, 3);  // 2
bool b = contains(v, 4);       // true
auto odd = indices_if(v, [](int x) { return x % 2 == 1; });  // {0, 1, 3, 4}

C++20 以降では、要件を満たすコンテナに ranges アルゴリズムを使います。std::vector<bool> など、従来のアルゴリズムで扱えて ranges の要件を満たさない場合は、従来の処理に切り替えます。コンテナ自身のメンバ関数を優先する規則は同じです。

並べ替え

関数 説明 計算量
sorted(c) / sorted(c, comp) / sorted(c, comp, proj) ソートしたコピーを返す。降順は sorted(c, std::greater<>())。proj を渡すと comp(proj(a), proj(b)) で比べる (std::ranges::sort と同じ。proj には &T::x のようなメンバポインタも渡せる)。キーだけなら sorted(c, {}, key) $O(n \log n)$
reversed(c) 逆順にしたコピーを返す $O(n)$
sort(c) / sort(c, comp) / sort(c, comp, proj) その場でソート。降順は sort(c, std::greater<>())。proj は sorted と同じ。キーだけなら sort(c, {}, key) $O(n \log n)$
reverse(c) その場で逆順にする $O(n)$

集計

関数 説明 計算量
max(c) / min(c) 最大値 / 最小値 (空なら assert で落ちる)。max({a, b, c}) のように初期化子リストも渡せる $O(n)$ (set などソート済みのコンテナでは $O(1)$)
sum(c) 総和 $O(n)$
product(c) 総積 $O(n)$
product_xor(c) 総 xor $O(n)$
gcd(c) 全要素の gcd (空なら 0) $O(n \log \max)$
average(c) 平均 (sum(c) / size、整数型なら 0 方向に切り捨て。空なら assert で落ちる) $O(n)$
median(c) 中央値 (要素数が偶数なら中央 2 つの平均。整数型の端数は小さい方へ丸める。空なら assert で落ちる) $O(n \log n)$
mex(c) 含まれない最小の非負整数 $O(n)$
hamming_distance(s, t) 同じ長さの列 s と t で要素が異なる位置の数 (long long。型が違ってもよく、string と vector<int> なども比べられる。長さが違うと assert で落ちる) $O(n)$

検索

関数 説明 計算量
find(c, x) x を指すイテレータ (なければ end()) $O(n)$ (set などでは $O(\log n)$)
count(c, x) x の個数 $O(n)$ (multiset などでは $O(\log n + k)$、$k$ は個数)
contains(c, x) x を含むか find と同じ
index(c, x) x が最初に現れる位置 (long long。なければ -1) $O(n)$
index_if(c, f) f(x) が true になる最初の位置 (long long。なければ -1) $O(n)$
indices_if(c, f) f(x) が true になる位置を昇順に並べたもの (std::vector<long long>) $O(n)$
count_if(c, f) f(x) が true になる要素の個数 (long long) $O(n)$
lower_bound(c, x) / upper_bound(c, x) イテレータを返す $O(\log n)$
bisect_left(c, x) / bisect_right(c, x) 添字を long long で返す (Python の bisect) $O(\log n)$ (set などでは位置を数えるので $O(n)$)

位置は、set などでは先頭から数えた順番です。

条件を満たす候補が 1 つだけのときに選ぶ、といった処理は indices_if で書けます。

// t と長さが同じで 1 文字だけ違う名前が、ちょうど 1 つあればその位置
auto cand = indices_if(names, [&](const std::string& s) { return s.size() == t.size() && hamming_distance(s, t) == 1; });
if (cand.size() == 1) vote[cand[0]]++;

関連

Depends on

Verified with

Code

#pragma once

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

#include <algorithm>
#include <cassert>
#include <cstddef>
#include <functional>
#include <initializer_list>
#include <iterator>
#include <numeric>
#include <type_traits>
#include <vector>

#include "../base/functions.hpp"
#include "traits.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/container_func.hpp"

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

#include <algorithm>
#include <cassert>
#include <cstddef>
#include <functional>
#include <initializer_list>
#include <iterator>
#include <numeric>
#include <type_traits>
#include <vector>

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

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

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

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 2 "src/utility/traits.hpp"

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

#line 11 "src/utility/traits.hpp"
#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 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)));
}
Back to top page