serna37's Library

Logo

C++ アルゴリズムとデータ構造のライブラリ

View the Project on GitHub serna37/library-cpp

:heavy_check_mark: 順列全探索
(library/search/permutation.hpp)

順列全探索

できること

計算量

$O(N!)$ Nは10〜12程度まで

使い方

// 関数でbreakしてたらtrue
bool is_loop_break = permutation(A, [&](){
    print(A);
    return true; // trueで探索をbreak
});

Verified with

Code

#pragma once
template <typename T, typename F> bool permutation(vector<T> &A, F f) {
    sort(begin(A), end(A));
    do {
        if (f()) return true;
    } while (next_permutation(begin(A), end(A)));
    return false;
}
#line 2 "library/search/permutation.hpp"
template <typename T, typename F> bool permutation(vector<T> &A, F f) {
    sort(begin(A), end(A));
    do {
        if (f()) return true;
    } while (next_permutation(begin(A), end(A)));
    return false;
}
Back to top page