next_permutation 枚举全排列的剪枝方法

· · 算法·理论

摘要

本文介绍剔除全排列的特定前缀的方法。

设需要剔除的前缀为 x,则剔除方法如下。

for (int i = 1; i <= n; ++i)
    a[i] = i;
do {
    int x = n + 1;
    ; // 如果需要剔除, 这里会给 x 赋值
    if (x <= n) {
        sort(a + x + 1, a + n + 1, greater<>());
        continue;
    }
} while (next_permutation(a + 1, a + n + 1));

本方法可以通过 prev_permutation 扩展到后缀。

示例

Luogu P3599 Koishi Loves Construction Task 1 的一个打表程序。

#include <algorithm>
#include <iostream>

#define int long long

using namespace std;

int n;
int a[100005];
bool vis[100005];

signed main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cin >> n;
    for (int i = 1; i <= n; ++i)
        a[i] = i;
    int cnt = 0;
    do {
        for (int i = 0; i < n; ++i)
            vis[i] = 0;
        int s = 0;
        int x = n + 1;
        for (int i = 1; i <= n; ++i) {
            s = (s + a[i]) % n;
            if (vis[s]) {
                x = i;
                break;
            }
            vis[s] = true;
        }
        if (x <= n) {
            sort(a + x + 1, a + n + 1, greater<>());
            continue;
        }
        ++cnt;
        if (a[1] == n && a[n] == n - 1) {
            cout << cnt << ": ";
            for (int i = 1; i <= n; ++i)
                cout << a[i] << ' ';
            cout << endl;
        }
    } while (next_permutation(a + 1, a + n + 1));
    cout << cnt << endl;
    return 0;
}