競技プログラミング用の C++ ライブラリ
#define PROBLEM "https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP1_1_A"
// Counter を std::map による愚直な実装とランダムに比較する
// 問題の入力は使わず、すべて一致したら Hello World を出力する
#include "../../../src/data_structures/counter.hpp"
#include <algorithm>
#include <iostream>
#include <map>
#include <random>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
#include "../../../src/utility/range.hpp"
using Model = std::map<int, long long>;
static_assert(!std::is_assignable_v<decltype((std::declval<Counter<int>&>().lower_bound(0)->second)), long long>);
static_assert(!std::is_assignable_v<decltype((std::declval<Counter<int>&>().upper_bound(0)->second)), long long>);
using FrequencyReference = decltype(std::declval<Counter<int>&>().by_frequency());
static_assert(std::is_lvalue_reference_v<FrequencyReference>);
static_assert(std::is_const_v<std::remove_reference_t<FrequencyReference>>);
static_assert(!std::is_assignable_v<decltype((std::declval<FrequencyReference>().begin()->second)), long long>);
// 個数 0 の値を取り除いた map にする
Model normalize(Model m) {
for (auto itr = m.begin(); itr != m.end();) {
if (itr->second == 0)
itr = m.erase(itr);
else
++itr;
}
return m;
}
bool same(const Counter<int>& c, const Model& m) {
Model mm = normalize(m);
if (c.size() != static_cast<int>(mm.size())) return false;
// total は重複を含めた要素数 (個数の総和)
long long sum = 0;
for (auto [x, cnt] : mm) sum += cnt;
if (c.total() != sum) return false;
// begin / end で走査した結果が値の昇順に一致する
std::vector<std::pair<int, long long>> a(c.begin(), c.end()), b(mm.begin(), mm.end());
if (a != b) return false;
// 頻度順の走査を、map から独立に並べ替えた列と比べる
std::stable_sort(b.begin(), b.end(), [](const auto& p, const auto& q) { return p.second > q.second; });
const auto& frequency = c.by_frequency();
if (std::vector<std::pair<int, long long>>(frequency.begin(), frequency.end()) != b) return false;
std::reverse(b.begin(), b.end());
if (std::vector<std::pair<int, long long>>(frequency.rbegin(), frequency.rend()) != b) return false;
// 最頻値は同数なら最小の値。空なら nullopt
auto mode = c.mode();
if (mm.empty()) {
if (mode) return false;
} else {
auto best = mm.begin();
for (auto itr = mm.begin(); itr != mm.end(); ++itr) {
if (itr->second > best->second) best = itr;
}
if (!mode || mode->value != best->first || mode->count != best->second) return false;
}
// const な [] と get
for (int x = -1; x <= 10; x++) {
long long expect = mm.count(x) ? mm.at(x) : 0;
if (c[x] != expect || c.get(x) != expect) return false;
const auto lower = c.lower_bound(x), upper = c.upper_bound(x);
const auto expected_lower = mm.lower_bound(x), expected_upper = mm.upper_bound(x);
if ((lower == c.end()) != (expected_lower == mm.end())) return false;
if ((upper == c.end()) != (expected_upper == mm.end())) return false;
if (lower != c.end() && *lower != *expected_lower) return false;
if (upper != c.end() && *upper != *expected_upper) return false;
}
return true;
}
Model random_model(std::mt19937& rng) {
Model m;
int k = rng() % 6;
for (int i = 0; i < k; i++) m[rng() % 10] += rng() % 4;
return m;
}
Counter<int> from_model(const Model& m) {
Counter<int> c;
for (auto [x, cnt] : m) c[x] = cnt;
return c;
}
int main() {
std::mt19937 rng(314);
bool ok = true;
auto check = [&](bool cond, const char* what) {
if (!cond && ok) {
std::cerr << "failed: " << what << std::endl;
ok = false;
}
};
// コンストラクタ
{
Counter<int> empty;
check(same(empty, {}), "default constructor");
Counter<int> one(5);
check(same(one, {{5, 1}}), "Counter(x)");
one.dec(5);
check(same(one, {}), "dec 省略時は 1、0 になった値を削除");
std::vector<int> v = {3, 1, 3, 2, 3};
Counter from_vec(v);
check(same(from_vec, {{1, 1}, {2, 1}, {3, 3}}), "Counter(range)");
Counter<int> from_il{{1, 2}, {4, 0}, {7, 3}, {1, 1}};
check(same(from_il, {{1, 3}, {7, 3}}), "Counter(initializer_list)");
// const でない左辺値からのコピーが範囲のコンストラクタに横取りされない
Counter<int> copy(from_vec);
check(same(copy, {{1, 1}, {2, 1}, {3, 3}}), "copy constructor");
// key_type が範囲でもある場合は値 1 個として数える
Counter<std::string> s(std::string("ab"));
check(s.size() == 1 && s["ab"] == 1, "Counter<std::string>(x)");
Counter<char> chars(std::string("aab"));
check(chars['a'] == 2 && chars['b'] == 1 && chars.size() == 2, "Counter<char>(string)");
// size は異なる値の個数、total は重複を含めた要素数
Counter<int> dup(std::vector<int>{3, 3, 3, 5});
check(dup.size() == 2 && dup.total() == 4, "size / total");
check(Counter<int>().total() == 0, "total of empty");
}
for (int rep = 0; rep < 3000 && ok; rep++) {
Model ma = random_model(rng), mb = random_model(rng);
Counter<int> a = from_model(ma), b = from_model(mb);
check(same(a, ma), "operator[] =");
// + と +=
Model sum = ma;
for (auto [x, cnt] : mb) sum[x] += cnt;
check(same(a + b, sum), "operator+");
Counter<int> c = a;
c += b;
check(same(c, sum), "operator+=");
// - と -= (個数が負にならない範囲で)
Model sub = sum;
for (auto [x, cnt] : mb) sub[x] -= cnt;
check(same(c - b, sub), "operator-");
c -= b;
check(same(c, sub), "operator-=");
// [] による += / -= / =
Counter<int> d = from_model(ma);
Model md = ma;
for (int t = 0; t < 20; t++) {
int x = rng() % 10;
int op = rng() % 3;
if (op == 0) {
long long k = rng() % 3;
d[x] += k;
md[x] += k;
} else if (op == 1) {
long long have = md.count(x) ? md[x] : 0;
long long k = have == 0 ? 0 : rng() % (have + 1);
d[x] -= k;
md[x] -= k;
} else {
long long k = rng() % 3;
d[x] = k;
md[x] = k;
}
check(same(d, md), "mode after update");
// 参照からの読み取り
long long expect = normalize(md).count(x) ? normalize(md).at(x) : 0;
check(static_cast<long long>(d[x]) == expect, "CounterReference -> mapped_type");
}
check(same(d, md), "operator[] += / -= / =");
// most_common: 個数の降順、同数なら値の昇順
Model nm = normalize(md);
std::vector<std::pair<int, long long>> expect(nm.begin(), nm.end());
std::stable_sort(expect.begin(), expect.end(), [](const auto& p, const auto& q) { return p.second > q.second; });
check(d.most_common() == expect, "most_common");
for (long long k = 0; k <= d.size() + 2; ++k) {
auto top = expect;
if (k < static_cast<long long>(top.size())) top.resize(k);
check(d.most_common(k) == top, "most_common(k)");
}
}
// 自分自身を引くと空になる (走査中の要素を消しても壊れない)
if (ok) {
Counter<int> c{{1, 2}, {3, 1}, {5, 4}};
c -= c;
check(same(c, {}), "self operator-=");
check(c.most_common(2).empty(), "most_common(k) of empty");
Counter<int> d{{1, 2}, {3, 1}};
d += d;
check(same(d, {{1, 4}, {3, 2}}), "self operator+=");
}
{
Counter<int> c{{1, 2}, {3, 2}, {5, 1}};
const auto& frequency = c.by_frequency();
check(*frequency.lower_bound({2, 2}) == std::make_pair(3, 2LL), "frequency lower_bound");
check(*frequency.upper_bound({3, 2}) == std::make_pair(5, 1LL), "frequency upper_bound");
c[5] += 3;
check(&frequency == &c.by_frequency() && *frequency.begin() == std::make_pair(5, 4LL), "frequency reference follows updates");
c[5] = 0;
check(frequency.size() == 2 && *frequency.rbegin() == std::make_pair(3, 2LL), "frequency reference follows erasure");
c -= c;
check(frequency.empty(), "frequency reference follows clearing");
}
{
const Range values(0, 10, 2);
Counter<long long> inferred(values);
check(inferred.size() == 5 && inferred.total() == 5 && inferred.get(4) == 1 && inferred.get(3) == 0, "Range constructor");
Counter<std::string> key(std::string("abc"));
Counter<std::string> copy(key);
check(copy.get("abc") == 1 && copy.total() == 1, "range-like key and copy constructor");
}
if (ok) std::cout << "Hello World" << std::endl;
}#line 1 "test/unittest/data_structures/counter.test.cpp"
#define PROBLEM "https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP1_1_A"
// Counter を std::map による愚直な実装とランダムに比較する
// 問題の入力は使わず、すべて一致したら Hello World を出力する
#line 2 "src/data_structures/counter.hpp"
/**
* @file counter.hpp
* @brief 値の個数を数える多重集合 (Counter)
*/
#include <cassert>
#include <cstddef>
#include <initializer_list>
#include <iterator>
#include <map>
#include <optional>
#include <set>
#include <type_traits>
#include <utility>
#include <vector>
#line 2 "src/utility/traits.hpp"
/**
* @file traits.hpp
* @brief 型特性
*/
#line 9 "src/utility/traits.hpp"
#include <functional>
#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/data_structures/counter.hpp"
template <typename T = long long>
struct Counter {
using key_type = T;
using mapped_type = long long;
using value_type = std::pair<key_type, mapped_type>;
private:
struct CompareFrequency {
bool operator()(const value_type& a, const value_type& b) const {
return a.second > b.second || (a.second == b.second && a.first < b.first);
}
};
std::map<key_type, mapped_type> data;
std::set<value_type, CompareFrequency> frequency;
mapped_type total_count = 0;
public:
void inc(const key_type& key, const mapped_type& t = 1) {
set(key, get(key) + t);
}
void dec(const key_type& key, const mapped_type& t = 1) {
set(key, get(key) - t);
}
Counter() = default;
explicit Counter(const key_type& x) { set(x, 1); }
/**
* @brief 範囲の要素を数える
* Counter 自身と key_type (std::string など範囲でもあるもの) はこちらで受け取らない
*/
#if __cplusplus >= 202002L
template <class C>
requires(!std::same_as<std::decay_t<C>, Counter> && !std::convertible_to<C, key_type> &&
requires(C& c) { std::begin(c); std::end(c); })
#else
template <class C, ENABLE_IF_T(!std::is_same_v<std::decay_t<C>, Counter> && !std::is_convertible_v<C, key_type>),
class = decltype(std::begin(std::declval<C&>()), std::end(std::declval<C&>()))>
#endif
explicit Counter(C&& v) {
for (const key_type& a : v) {
inc(a);
}
}
Counter(std::initializer_list<value_type> init) {
for (const auto& p : init) {
inc(p.first, p.second);
}
}
Counter& operator+=(const Counter& o) {
for (const auto& [i, c] : o.data) {
inc(i, c);
}
return *this;
}
friend Counter operator+(const Counter& a, const Counter& b) {
Counter res(a);
return res += b;
}
Counter& operator-=(const Counter& o) {
// 自分自身を引くと、走査中の o.data の要素を dec が消してしまう
if (this == &o) {
data.clear();
frequency.clear();
total_count = 0;
return *this;
}
for (const auto& [i, c] : o.data) {
dec(i, c);
}
return *this;
}
friend Counter operator-(const Counter& a, const Counter& b) {
Counter res(a);
return res -= b;
}
auto begin() const { return data.begin(); }
auto end() const { return data.end(); }
/** @brief key 以上の最初の値の読み取り専用イテレータ (なければ end()) */
auto lower_bound(const key_type& key) const { return data.lower_bound(key); }
/** @brief key より大きい最初の値の読み取り専用イテレータ (なければ end()) */
auto upper_bound(const key_type& key) const { return data.upper_bound(key); }
/**
* @brief 異なる値の個数 (重複は数えない)
*/
long long size() const {
return static_cast<long long>(data.size());
}
/**
* @brief 重複を含めた要素数 (個数の総和)
* @note Python の collections.Counter.total() と同じ。O(1)
*/
mapped_type total() const {
return total_count;
}
mapped_type get(const key_type& key) const {
auto itr = data.find(key);
if (itr == data.end()) return 0;
return itr->second;
}
void set(const key_type& key, const mapped_type& t) {
assert(t >= 0);
auto itr = data.find(key);
total_count += t - (itr == data.end() ? 0 : itr->second);
if (itr != data.end()) frequency.erase(*itr);
if (t > 0) {
data[key] = t;
frequency.emplace(key, t);
} else if (itr != data.end()) {
data.erase(itr);
}
}
struct Mode {
T value;
long long count;
};
/**
* @brief 最頻値とその個数を返す。同数なら最小の値を選び、空なら std::nullopt を返す
* @note O(1)
*/
std::optional<Mode> mode() const {
if (frequency.empty()) return std::nullopt;
const auto& [value, count] = *frequency.begin();
return Mode{value, count};
}
/**
* @brief 個数の降順、同数なら値の昇順に並べた内部 set の const 参照 (コピーしない)
* @note O(1)。Counter の更新は参照先にも反映される。更新した値の要素へのイテレータは失効する
*/
const auto& by_frequency() const { return frequency; }
std::vector<value_type> most_common() const {
return {frequency.begin(), frequency.end()};
}
/**
* @brief 個数の多い順に上位 k 件を返す。同数なら値の昇順。k >= 0
* @note k が異なる値の個数より大きければ全件を返す。O(min(k, size()))
*/
std::vector<value_type> most_common(long long k) const {
assert(k >= 0);
if (k > size()) k = size();
std::vector<value_type> result;
result.reserve(k);
auto itr = frequency.begin();
for (long long i = 0; i < k; ++i, ++itr) result.push_back(*itr);
return result;
}
class CounterReference {
Counter& base;
key_type key;
public:
CounterReference(Counter& base, key_type key) : base(base), key(key) {}
CounterReference& operator=(const mapped_type& x) {
base.set(key, x);
return *this;
}
CounterReference& operator+=(const mapped_type& x) {
base.inc(key, x);
return *this;
}
CounterReference& operator-=(const mapped_type& x) {
base.dec(key, x);
return *this;
}
operator mapped_type() const {
return base.get(key);
}
};
mapped_type operator[](const key_type& key) const {
return get(key);
}
CounterReference operator[](const key_type& key) {
return CounterReference(*this, key);
}
};
template <typename T>
Counter(std::vector<T>) -> Counter<T>;
#line 7 "test/unittest/data_structures/counter.test.cpp"
#include <algorithm>
#include <iostream>
#line 11 "test/unittest/data_structures/counter.test.cpp"
#include <random>
#include <string>
#line 16 "test/unittest/data_structures/counter.test.cpp"
#line 2 "src/utility/range.hpp"
/**
* @file range.hpp
* @brief Python の range のような整数列と、その直積の Grid
*/
#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 18 "test/unittest/data_structures/counter.test.cpp"
using Model = std::map<int, long long>;
static_assert(!std::is_assignable_v<decltype((std::declval<Counter<int>&>().lower_bound(0)->second)), long long>);
static_assert(!std::is_assignable_v<decltype((std::declval<Counter<int>&>().upper_bound(0)->second)), long long>);
using FrequencyReference = decltype(std::declval<Counter<int>&>().by_frequency());
static_assert(std::is_lvalue_reference_v<FrequencyReference>);
static_assert(std::is_const_v<std::remove_reference_t<FrequencyReference>>);
static_assert(!std::is_assignable_v<decltype((std::declval<FrequencyReference>().begin()->second)), long long>);
// 個数 0 の値を取り除いた map にする
Model normalize(Model m) {
for (auto itr = m.begin(); itr != m.end();) {
if (itr->second == 0)
itr = m.erase(itr);
else
++itr;
}
return m;
}
bool same(const Counter<int>& c, const Model& m) {
Model mm = normalize(m);
if (c.size() != static_cast<int>(mm.size())) return false;
// total は重複を含めた要素数 (個数の総和)
long long sum = 0;
for (auto [x, cnt] : mm) sum += cnt;
if (c.total() != sum) return false;
// begin / end で走査した結果が値の昇順に一致する
std::vector<std::pair<int, long long>> a(c.begin(), c.end()), b(mm.begin(), mm.end());
if (a != b) return false;
// 頻度順の走査を、map から独立に並べ替えた列と比べる
std::stable_sort(b.begin(), b.end(), [](const auto& p, const auto& q) { return p.second > q.second; });
const auto& frequency = c.by_frequency();
if (std::vector<std::pair<int, long long>>(frequency.begin(), frequency.end()) != b) return false;
std::reverse(b.begin(), b.end());
if (std::vector<std::pair<int, long long>>(frequency.rbegin(), frequency.rend()) != b) return false;
// 最頻値は同数なら最小の値。空なら nullopt
auto mode = c.mode();
if (mm.empty()) {
if (mode) return false;
} else {
auto best = mm.begin();
for (auto itr = mm.begin(); itr != mm.end(); ++itr) {
if (itr->second > best->second) best = itr;
}
if (!mode || mode->value != best->first || mode->count != best->second) return false;
}
// const な [] と get
for (int x = -1; x <= 10; x++) {
long long expect = mm.count(x) ? mm.at(x) : 0;
if (c[x] != expect || c.get(x) != expect) return false;
const auto lower = c.lower_bound(x), upper = c.upper_bound(x);
const auto expected_lower = mm.lower_bound(x), expected_upper = mm.upper_bound(x);
if ((lower == c.end()) != (expected_lower == mm.end())) return false;
if ((upper == c.end()) != (expected_upper == mm.end())) return false;
if (lower != c.end() && *lower != *expected_lower) return false;
if (upper != c.end() && *upper != *expected_upper) return false;
}
return true;
}
Model random_model(std::mt19937& rng) {
Model m;
int k = rng() % 6;
for (int i = 0; i < k; i++) m[rng() % 10] += rng() % 4;
return m;
}
Counter<int> from_model(const Model& m) {
Counter<int> c;
for (auto [x, cnt] : m) c[x] = cnt;
return c;
}
int main() {
std::mt19937 rng(314);
bool ok = true;
auto check = [&](bool cond, const char* what) {
if (!cond && ok) {
std::cerr << "failed: " << what << std::endl;
ok = false;
}
};
// コンストラクタ
{
Counter<int> empty;
check(same(empty, {}), "default constructor");
Counter<int> one(5);
check(same(one, {{5, 1}}), "Counter(x)");
one.dec(5);
check(same(one, {}), "dec 省略時は 1、0 になった値を削除");
std::vector<int> v = {3, 1, 3, 2, 3};
Counter from_vec(v);
check(same(from_vec, {{1, 1}, {2, 1}, {3, 3}}), "Counter(range)");
Counter<int> from_il{{1, 2}, {4, 0}, {7, 3}, {1, 1}};
check(same(from_il, {{1, 3}, {7, 3}}), "Counter(initializer_list)");
// const でない左辺値からのコピーが範囲のコンストラクタに横取りされない
Counter<int> copy(from_vec);
check(same(copy, {{1, 1}, {2, 1}, {3, 3}}), "copy constructor");
// key_type が範囲でもある場合は値 1 個として数える
Counter<std::string> s(std::string("ab"));
check(s.size() == 1 && s["ab"] == 1, "Counter<std::string>(x)");
Counter<char> chars(std::string("aab"));
check(chars['a'] == 2 && chars['b'] == 1 && chars.size() == 2, "Counter<char>(string)");
// size は異なる値の個数、total は重複を含めた要素数
Counter<int> dup(std::vector<int>{3, 3, 3, 5});
check(dup.size() == 2 && dup.total() == 4, "size / total");
check(Counter<int>().total() == 0, "total of empty");
}
for (int rep = 0; rep < 3000 && ok; rep++) {
Model ma = random_model(rng), mb = random_model(rng);
Counter<int> a = from_model(ma), b = from_model(mb);
check(same(a, ma), "operator[] =");
// + と +=
Model sum = ma;
for (auto [x, cnt] : mb) sum[x] += cnt;
check(same(a + b, sum), "operator+");
Counter<int> c = a;
c += b;
check(same(c, sum), "operator+=");
// - と -= (個数が負にならない範囲で)
Model sub = sum;
for (auto [x, cnt] : mb) sub[x] -= cnt;
check(same(c - b, sub), "operator-");
c -= b;
check(same(c, sub), "operator-=");
// [] による += / -= / =
Counter<int> d = from_model(ma);
Model md = ma;
for (int t = 0; t < 20; t++) {
int x = rng() % 10;
int op = rng() % 3;
if (op == 0) {
long long k = rng() % 3;
d[x] += k;
md[x] += k;
} else if (op == 1) {
long long have = md.count(x) ? md[x] : 0;
long long k = have == 0 ? 0 : rng() % (have + 1);
d[x] -= k;
md[x] -= k;
} else {
long long k = rng() % 3;
d[x] = k;
md[x] = k;
}
check(same(d, md), "mode after update");
// 参照からの読み取り
long long expect = normalize(md).count(x) ? normalize(md).at(x) : 0;
check(static_cast<long long>(d[x]) == expect, "CounterReference -> mapped_type");
}
check(same(d, md), "operator[] += / -= / =");
// most_common: 個数の降順、同数なら値の昇順
Model nm = normalize(md);
std::vector<std::pair<int, long long>> expect(nm.begin(), nm.end());
std::stable_sort(expect.begin(), expect.end(), [](const auto& p, const auto& q) { return p.second > q.second; });
check(d.most_common() == expect, "most_common");
for (long long k = 0; k <= d.size() + 2; ++k) {
auto top = expect;
if (k < static_cast<long long>(top.size())) top.resize(k);
check(d.most_common(k) == top, "most_common(k)");
}
}
// 自分自身を引くと空になる (走査中の要素を消しても壊れない)
if (ok) {
Counter<int> c{{1, 2}, {3, 1}, {5, 4}};
c -= c;
check(same(c, {}), "self operator-=");
check(c.most_common(2).empty(), "most_common(k) of empty");
Counter<int> d{{1, 2}, {3, 1}};
d += d;
check(same(d, {{1, 4}, {3, 2}}), "self operator+=");
}
{
Counter<int> c{{1, 2}, {3, 2}, {5, 1}};
const auto& frequency = c.by_frequency();
check(*frequency.lower_bound({2, 2}) == std::make_pair(3, 2LL), "frequency lower_bound");
check(*frequency.upper_bound({3, 2}) == std::make_pair(5, 1LL), "frequency upper_bound");
c[5] += 3;
check(&frequency == &c.by_frequency() && *frequency.begin() == std::make_pair(5, 4LL), "frequency reference follows updates");
c[5] = 0;
check(frequency.size() == 2 && *frequency.rbegin() == std::make_pair(3, 2LL), "frequency reference follows erasure");
c -= c;
check(frequency.empty(), "frequency reference follows clearing");
}
{
const Range values(0, 10, 2);
Counter<long long> inferred(values);
check(inferred.size() == 5 && inferred.total() == 5 && inferred.get(4) == 1 && inferred.get(3) == 0, "Range constructor");
Counter<std::string> key(std::string("abc"));
Counter<std::string> copy(key);
check(copy.get("abc") == 1 && copy.total() == 1, "range-like key and copy constructor");
}
if (ok) std::cout << "Hello World" << std::endl;
}