compro_library

This documentation is automatically generated by online-judge-tools/verification-helper

View the Project on GitHub siro53/compro_library

:heavy_check_mark: ランダムな数列・順列・部分集合・区間
(random/gen/sequence.hpp)

このライブラリでできること

ランダムテストの入力でよく使う数列を、Random から生成する関数群です。

どの関数も、取り得る結果の上で一様分布になるように選びます。数列の範囲はすべて右端を含まない半開区間です。

使い方

第1引数に Random を渡し、続けて長さと値の範囲を渡します。例では、$1$ 以上 $9$ 以下の値からなる長さ $5$ の数列、$0$ 以上 $99$ 以下の相異なる $3$ 個、長さ $4$ の順列、区間を作っています。

#include "template/template.cpp"
#include "random/gen/sequence.hpp"

int main(int argc, char **argv) {
    Random rng(argc, argv);
    vector<int> a = random_vector(rng, 5, 1, 10);
    for(int x : a) assert(1 <= x && x < 10);

    vector<int> d = random_distinct_vector(rng, 3, 0, 100);
    assert(set<int>(d.begin(), d.end()).size() == 3);

    vector<int> p = random_permutation(rng, 4);   // 0, 1, 2, 3 の並べ替え
    vector<int> s = random_subset(rng, 10, 3);    // 昇順の 3 要素
    assert(s.size() == 3 && is_sorted(s.begin(), s.end()));

    auto [l, r] = random_interval(rng, 0, 5);     // 0 <= l < r <= 5
    assert(0 <= l && l < r && r <= 5);

    // 1-indexed の順列と閉区間 [l+1, r] で出力する
    for(int &x : p) x++;
    print(p);
    print(l + 1, r);
}

順列は0始まりで返すので、1始まりで出力する場合は例のように $1$ を足します。random_interval の結果 $[l,r)$ は、閉区間 $[l+1,r]$ と書く1始まりの形式に変換できます。

API・計算量

以下では、生成する長さを $n$ または $k$、値の範囲の幅を $w=r-l$ とします。各関数は結果の vector として $O(n)$ の領域を使い、random_distinct_vector は選んだ値を記録するハッシュ集合として追加で $O(n)$ を使います。

API 動作・返り値 時間計算量
random_vector(rng, n, l, r) 各要素が独立に $[l,r)$ の一様乱数である長さ $n$ の vector。要素型は l, r, int の共通型。 期待 $O(n)$
random_distinct_vector(rng, n, l, r) $[l,r)$ の $n$ 元部分集合を一様に選び、一様ランダムな順に並べた vector。 期待 $O(n)$
random_permutation(rng, n) $(0,\dots,n-1)$ の一様ランダムな順列。 期待 $O(n)$
random_subset(rng, n, k) ${0,\dots,n-1}$ の $k$ 元部分集合を一様に選び、昇順で返す。 期待 $O(k \log k)$
random_interval(rng, l, r) $l \le a < b \le r$ を満たす $(a,b)$ を一様に選び、pair で返す。 期待 $O(1)$

random_distinct_vector は Floyd のサンプリングで値を選びます。$j=w-n,\dots,w-1$ の順に $t \in [0,j]$ を一様に引き、$t$ が選択済みなら代わりに $j$ を選びます。こうすると、$n$ 元部分集合のどれもが等確率で得られます。その後で全体をシャッフルするため、並び順も一様です。ハッシュ集合の操作は期待 $O(1)$ として計算量を示しています。

利用条件と実装上の注意

Depends on

Required by

Verified with

Code

#pragma once

#include <algorithm>
#include <cassert>
#include <cstdint>
#include <numeric>
#include <type_traits>
#include <unordered_set>
#include <utility>
#include <vector>

#include "random.hpp"

// 各要素が [l, r) の一様乱数である長さ n の数列
template <class T, class U>
std::vector<std::common_type_t<T, U, int>> random_vector(Random &rng, int n,
                                                         T l, U r) {
    assert(n >= 0);
    std::vector<std::common_type_t<T, U, int>> v(n);
    for(auto &x : v) x = rng.randint(l, r);
    return v;
}

// [l, r) から相異なる n 個を一様に選び、ランダムな順に並べた数列
// (Floyd のサンプリング)
template <class T, class U>
std::vector<std::common_type_t<T, U, int>>
random_distinct_vector(Random &rng, int n, T l, U r) {
    using C = std::common_type_t<T, U, int>;
    using UC = std::make_unsigned_t<C>;
    const C lo = C(l), hi = C(r);
    assert(n >= 0 && lo <= hi);
    const std::uint64_t width = std::uint64_t(UC(hi) - UC(lo));
    assert(std::uint64_t(n) <= width);
    std::unordered_set<std::uint64_t> used;
    used.reserve(std::size_t(n) * 2);
    std::vector<C> v;
    v.reserve(n);
    for(std::uint64_t j = width - std::uint64_t(n); j < width; j++) {
        std::uint64_t t = rng.uniform(j + 1);
        if(used.count(t)) t = j;
        used.insert(t);
        v.push_back(C(UC(lo) + UC(t)));
    }
    rng.shuffle(v);
    return v;
}

// (0, 1, ..., n-1) の一様ランダムな順列
inline std::vector<int> random_permutation(Random &rng, int n) {
    assert(n >= 0);
    std::vector<int> p(n);
    std::iota(p.begin(), p.end(), 0);
    rng.shuffle(p);
    return p;
}

// {0, 1, ..., n-1} の大きさ k の部分集合を一様に選び、昇順で返す
inline std::vector<int> random_subset(Random &rng, int n, int k) {
    assert(0 <= k && k <= n);
    std::vector<int> s = random_distinct_vector(rng, k, 0, n);
    std::sort(s.begin(), s.end());
    return s;
}

// l <= a < b <= r を満たす半開区間 [a, b) を一様に選ぶ
template <class T, class U>
std::pair<std::common_type_t<T, U, int>, std::common_type_t<T, U, int>>
random_interval(Random &rng, T l, U r) {
    using C = std::common_type_t<T, U, int>;
    const C lo = C(l), hi = C(r);
    assert(lo < hi);
    // {lo, ..., hi} から相異なる 2 点を選ぶ
    std::vector<C> e = random_distinct_vector(rng, 2, lo, C(hi + 1));
    if(e[0] > e[1]) std::swap(e[0], e[1]);
    return {e[0], e[1]};
}
#line 2 "random/gen/sequence.hpp"

#include <algorithm>
#include <cassert>
#include <cstdint>
#include <numeric>
#include <type_traits>
#include <unordered_set>
#include <utility>
#include <vector>

#line 2 "random/gen/random.hpp"

#line 5 "random/gen/random.hpp"
#include <cerrno>
#include <cmath>
#line 8 "random/gen/random.hpp"
#include <cstdlib>
#include <iostream>
#include <random>
#line 14 "random/gen/random.hpp"

// seed を指定できる、ランダムテストの入力生成用の乱数
class Random {
  public:
    explicit Random(std::uint64_t seed = 0) : mt(seed) {}
    // argv[1] を seed として読む。引数がなければ seed = 0
    Random(int argc, char **argv) : mt(parse_seed(argc, argv)) {}

    // [0, n) の一様な整数 (n > 0)
    std::uint64_t uniform(std::uint64_t n) {
        assert(n > 0);
        // 2^64 mod n 個の値を棄却して剰余の偏りをなくす
        const std::uint64_t threshold = (0 - n) % n;
        std::uint64_t x = mt();
        while(x < threshold) x = mt();
        return x % n;
    }

    // [l, r) の一様な整数
    template <class T, class U>
    std::common_type_t<T, U, int> randint(T l, U r) {
        using C = std::common_type_t<T, U, int>;
        static_assert(std::is_integral<C>::value, "randint requires integers");
        const C lo = C(l), hi = C(r);
        assert(lo < hi);
        using UC = std::make_unsigned_t<C>;
        const std::uint64_t width = std::uint64_t(UC(hi) - UC(lo));
        return C(UC(lo) + UC(uniform(width)));
    }
    // [0, r) の一様な整数
    template <class T> std::common_type_t<T, int> randint(T r) {
        return randint(T(0), r);
    }

    // [l, r) に含まれる偶数から一様に選ぶ (偶数が 1 つ以上あること)
    template <class T, class U>
    std::common_type_t<T, U, int> even(T l, U r) {
        return with_parity(l, r, 0);
    }
    // [0, r) に含まれる偶数から一様に選ぶ
    template <class T> std::common_type_t<T, int> even(T r) {
        return even(T(0), r);
    }

    // [l, r) に含まれる奇数から一様に選ぶ (奇数が 1 つ以上あること)
    template <class T, class U>
    std::common_type_t<T, U, int> odd(T l, U r) {
        return with_parity(l, r, 1);
    }
    // [0, r) に含まれる奇数から一様に選ぶ
    template <class T> std::common_type_t<T, int> odd(T r) {
        return odd(T(0), r);
    }

    // [l, r) の実数 (53 bit の分解能)
    double real(double l, double r) {
        assert(l < r);
        const double u = double(mt() >> 11) / double(std::uint64_t(1) << 53);
        const double x = l + (r - l) * u;
        return x < r ? x : std::nextafter(r, l);
    }
    double real() { return real(0.0, 1.0); }

    // 確率 p で true
    bool coin(double p = 0.5) { return real() < p; }

    // 小さい値に偏らせた [l, r) の整数
    // 2 冪のスケール 1, 2, 4, ... を等確率で選び、その範囲で一様に選ぶ
    template <class T, class U>
    std::common_type_t<T, U, int> size(T l, U r) {
        using C = std::common_type_t<T, U, int>;
        const C lo = C(l), hi = C(r);
        assert(lo < hi);
        using UC = std::make_unsigned_t<C>;
        const std::uint64_t width = std::uint64_t(UC(hi) - UC(lo));
        int scales = 0;
        while(scales < 64 && (std::uint64_t(1) << scales) < width) scales++;
        const int k = int(uniform(std::uint64_t(scales + 1)));
        const std::uint64_t w = k >= 64 ? width : std::min(width, std::uint64_t(1) << k);
        return C(UC(lo) + UC(uniform(w)));
    }

    // v の要素を一様に 1 つ選ぶ (v は空でない)
    template <class T> const T &choice(const std::vector<T> &v) {
        assert(!v.empty());
        return v[uniform(v.size())];
    }

    // Fisher-Yates で v を一様にシャッフルする
    template <class T> void shuffle(std::vector<T> &v) {
        for(std::size_t i = v.size(); i > 1; i--) {
            std::swap(v[i - 1], v[uniform(i)]);
        }
    }

    // 標準の分布と組み合わせる場合のエンジン
    std::mt19937_64 &engine() { return mt; }

  private:
    std::mt19937_64 mt;

    // [l, r) のうち 2 で割った余りが parity (負の数も含めて数学的な偶奇) の値から一様に選ぶ
    template <class T, class U>
    std::common_type_t<T, U, int> with_parity(T l, U r, unsigned parity) {
        using C = std::common_type_t<T, U, int>;
        static_assert(std::is_integral<C>::value, "even/odd requires integers");
        using UC = std::make_unsigned_t<C>;
        const C lo = C(l), hi = C(r);
        assert(lo < hi);
        const std::uint64_t width = std::uint64_t(UC(hi) - UC(lo));
        // 2 の補数表現では UC への変換で偶奇が保たれる
        const std::uint64_t first = (std::uint64_t(UC(lo)) & 1) == parity ? 0 : 1;
        assert(first < width && "no integer of the requested parity in [l, r)");
        // first, first + 2, ... < width の個数 (width - first + 1 のあふれを避ける)
        const std::uint64_t count = (width - first - 1) / 2 + 1;
        return C(UC(lo) + UC(first + 2 * uniform(count)));
    }

    static std::uint64_t parse_seed(int argc, char **argv) {
        if(argc < 2) return 0;
        const char *s = argv[1];
        char *end = nullptr;
        errno = 0;
        const unsigned long long seed = std::strtoull(s, &end, 10);
        if(*s == '\0' || *s == '-' || *end != '\0' || errno == ERANGE) {
            std::cerr << "Random: invalid seed '" << s << "'\n";
            std::exit(2);
        }
        return seed;
    }
};
#line 13 "random/gen/sequence.hpp"

// 各要素が [l, r) の一様乱数である長さ n の数列
template <class T, class U>
std::vector<std::common_type_t<T, U, int>> random_vector(Random &rng, int n,
                                                         T l, U r) {
    assert(n >= 0);
    std::vector<std::common_type_t<T, U, int>> v(n);
    for(auto &x : v) x = rng.randint(l, r);
    return v;
}

// [l, r) から相異なる n 個を一様に選び、ランダムな順に並べた数列
// (Floyd のサンプリング)
template <class T, class U>
std::vector<std::common_type_t<T, U, int>>
random_distinct_vector(Random &rng, int n, T l, U r) {
    using C = std::common_type_t<T, U, int>;
    using UC = std::make_unsigned_t<C>;
    const C lo = C(l), hi = C(r);
    assert(n >= 0 && lo <= hi);
    const std::uint64_t width = std::uint64_t(UC(hi) - UC(lo));
    assert(std::uint64_t(n) <= width);
    std::unordered_set<std::uint64_t> used;
    used.reserve(std::size_t(n) * 2);
    std::vector<C> v;
    v.reserve(n);
    for(std::uint64_t j = width - std::uint64_t(n); j < width; j++) {
        std::uint64_t t = rng.uniform(j + 1);
        if(used.count(t)) t = j;
        used.insert(t);
        v.push_back(C(UC(lo) + UC(t)));
    }
    rng.shuffle(v);
    return v;
}

// (0, 1, ..., n-1) の一様ランダムな順列
inline std::vector<int> random_permutation(Random &rng, int n) {
    assert(n >= 0);
    std::vector<int> p(n);
    std::iota(p.begin(), p.end(), 0);
    rng.shuffle(p);
    return p;
}

// {0, 1, ..., n-1} の大きさ k の部分集合を一様に選び、昇順で返す
inline std::vector<int> random_subset(Random &rng, int n, int k) {
    assert(0 <= k && k <= n);
    std::vector<int> s = random_distinct_vector(rng, k, 0, n);
    std::sort(s.begin(), s.end());
    return s;
}

// l <= a < b <= r を満たす半開区間 [a, b) を一様に選ぶ
template <class T, class U>
std::pair<std::common_type_t<T, U, int>, std::common_type_t<T, U, int>>
random_interval(Random &rng, T l, U r) {
    using C = std::common_type_t<T, U, int>;
    const C lo = C(l), hi = C(r);
    assert(lo < hi);
    // {lo, ..., hi} から相異なる 2 点を選ぶ
    std::vector<C> e = random_distinct_vector(rng, 2, lo, C(hi + 1));
    if(e[0] > e[1]) std::swap(e[0], e[1]);
    return {e[0], e[1]};
}
Back to top page