不剪枝要走多少个结点
把 1 到 5 排成一排,要求挨着的两个不能是连号。这个版本先把 5 个位置全排满,最后才检查。运行它,看走过了多少个结点:
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct Stat {
int c = 0; // 找到几个解
int v = 0; // 走过几个结点
};
void naive_dfs(int n, vector<int>& path, vector<bool>& used, Stat& st) {
st.v++;
if ((int)path.size() == n) {
for (int i = 0; i + 1 < n; i++) {
if (abs(path[i] - path[i + 1]) == 1) return;
}
st.c++;
return;
}
for (int x = 1; x <= n; x++) {
if (used[x]) continue;
used[x] = true;
path.push_back(x);
naive_dfs(n, path, used, st);
path.pop_back();
used[x] = false;
}
}
Stat naive(int n) {
Stat st;
vector<int> path;
vector<bool> used(n + 1, false);
naive_dfs(n, path, used, st);
return st;
}
int main() {
cout << naive(5).v << endl;
}
(本题用 g++ -std=c++17 -O0 编译。)
全部评论