四项一起对得上吗

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

运行下面这段程序:

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

void perm_dfs(const vector<int>& a, vector<int>& path, vector<bool>& used, vector<vector<int>>& res) {
    if (path.size() == a.size()) {
        res.push_back(path);
        return;
    }
    for (size_t i = 0; i < a.size(); i++) {
        if (used[i]) continue;
        used[i] = true;
        path.push_back(a[i]);
        perm_dfs(a, path, used, res);
        used[i] = false;
        path.pop_back();
    }
}

vector<vector<int>> perm(const vector<int>& a) {
    vector<vector<int>> res;
    vector<int> path;
    vector<bool> used(a.size(), false);
    perm_dfs(a, path, used, res);
    return res;
}

void subs_dfs(const vector<int>& a, int s, vector<int>& path, vector<vector<int>>& res) {
    res.push_back(path);
    for (int i = s; i < (int)a.size(); i++) {
        path.push_back(a[i]);
        subs_dfs(a, i + 1, path, res);
        path.pop_back();
    }
}

vector<vector<int>> subs(const vector<int>& a) {
    vector<vector<int>> res;
    vector<int> path;
    subs_dfs(a, 0, path, res);
    return res;
}

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;
}

bool queen_ok(const vector<int>& col, int c) {
    int r = (int)col.size();
    for (int i = 0; i < r; i++) {
        if (col[i] == c || abs(col[i] - c) == r - i) return false;
    }
    return true;
}

void queens_dfs(int n, vector<int>& col, Stat& st) {
    st.v++;
    if ((int)col.size() == n) {
        st.c++;
        return;
    }
    for (int c = 0; c < n; c++) {
        if (!queen_ok(col, c)) continue;
        col.push_back(c);
        queens_dfs(n, col, st);
        col.pop_back();
    }
}

Stat queens(int n) {
    Stat st;
    vector<int> col;
    queens_dfs(n, col, st);
    return st;
}

int main() {
    Stat p = pruned(5);
    bool ok4 = perm({1, 2, 3}).size() == 6 && subs({1, 2, 3}).size() == 8
               && p.c == 14 && p.v == 70 && queens(4).c == 2;
    cout << boolalpha << ok4 << endl;
}

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

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

                        
👩‍🏫
AI
💬 题目评论

全部评论