Altered Algorithm

This commit is contained in:
e2hang
2025-09-01 19:49:15 +08:00
parent e162486df1
commit 9c30eb42e2
15 changed files with 954 additions and 0 deletions

View File

@@ -0,0 +1,59 @@
#include <iostream>
#include <vector>
using namespace std;
vector<vector<int>> result;
bool prime(int x){
if(x <= 1) return false;
for(int i = 2; i * i <= x; i++){
if(x % i == 0) return false;
}
return true;
}
bool checkPrime(int n, vector<int>& x) {
if (x.size() < 2) return true; // <20><><EFBFBD><EFBFBD>2<EFBFBD><32><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ü<EFBFBD><C3BC><EFBFBD>
int tmp = x[x.size() - 1] + x[x.size() - 2];
if (!prime(tmp)) return false;
if (x.size() == n) {
if (!prime(x.back() + x[0])) return false;
}
return true;
}
void dfs(int n, vector<int>& _path, vector<bool>& _used){
if(!checkPrime(n, _path)) return;
if(_path.size() == n){
result.push_back(_path);
return;
}
for(int i = 0; i < n; i++){
if(!_used[i]){
_used[i] = true;
_path.push_back(i + 1);
dfs(n, _path, _used);
_used[i] = false;
_path.pop_back();
}
}
}
int main(){
int n;
cin >> n;
vector<bool> used(n, false);
vector<int> path;
dfs(n, path, used);
for(auto x : result){
for(auto y : x){
cout << y << " ";
}
cout << endl;
}
cout << endl;
system("pause");
return 0;
}