剪枝之后呢

👁️ 2 人浏览 💬 0 人评论 ❤️ 添加收藏

同一个问题,这个版本放的时候就检查是不是连号,是就不往下走。运行它:

#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
using namespace std;

struct Stat {
    int c = 0;   // 找到几个解
    int v = 0;   // 走过几个结点
};

void pruned_dfs(int n, vector<int>& path, vector<bool>& used, Stat& st) {
    st.v++;
    if ((int)path.size() == n) {
        st.c++;
        return;
    }
    for (int x = 1; x <= n; x++) {
        if (used[x]) continue;
        if (!path.empty() && abs(path.back() - x) == 1) continue;
        used[x] = true;
        path.push_back(x);
        pruned_dfs(n, path, used, st);
        path.pop_back();
        used[x] = false;
    }
}

Stat pruned(int n) {
    Stat st;
    vector<int> path;
    vector<bool> used(n + 1, false);
    pruned_dfs(n, path, used, st);
    return st;
}

int main() {
    cout << pruned(5).v << endl;
}

(本题用 g++ -std=c++17 -O0 编译。)

提交你的答案
请登录后提交答案。
去登录
代码编辑器
Ctrl + Enter 运行
本次输入:
输出:

                        
👩‍🏫
AI
💬 题目评论

全部评论