纯深搜
#include<iostream>
#include<algorithm>
#include<vector>
#include<fstream>
using namespace std;
int status[21]; //status[i]==0表示当前路径path包含i
ofstream out("output.txt");
bool isPrime(int n){
if(n==2) return true;
if(n==1||n%2==0) return false;
int k = sqrt(n);
for(int i=3;i<=k;i+=2) if(n%i==0) return false;
return true;
}
bool dfs(vector<int> &path, vector<vector<int> > &res){
if(path.size()==20){
res.push_back(path);
for(auto &i:path) out<<i<<" "; out<<endl;
return true;
}
int i;
for(i=1;i<=20;i++){
if(status[i]==0) continue;
if(!path.empty()){
if(!isPrime(path.back()+i)) continue;
else{
if(path.size()==19 && !isPrime(path[0]+i)) continue;
else;
}
}
//当前将i加入path是合适的
status[i]--;
path.push_back(i);
dfs(path,res);
status[i]++;
path.pop_back();
}
}
int main(){
//初始化status
for(int i=1;i<=20;i++) status[i]=1;
vector<int> path;
vector<vector<int> > res;
dfs(path,res);
cout<<"done!"<<endl;
return 0;
}