Files
Data-Structure/Algorithm/BackTracking/UVa524-PrimeRingProblem.cpp
2025-09-01 19:49:15 +08:00

60 lines
1.1 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#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; // ÉÙÓÚ2¸ö£¬²»Óüì²é
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;
}