标签:dfs
dfs 确定每一个位置上填写的数字
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <math.h>
using namespace std;
int n;
int A[18];
int p[40];
int vis[18];
int is_prime(int n){
for(int i = 2; i<sqrt(n+1);i++) if(n%i==0) return 0;
return 1;
}
void dfs(int cur){
if(cur == n && p[A[0]+A[n-1]]){
for(int i=0;i<n-1;i++) cout<<A[i]<<" ";
cout<<A[n-1]<<endl;
}
else for(int i=2;i<=n;i++){
if(!vis[i] && p[i+A[cur-1]]){
A[cur] = i;
vis[i] = 1;
dfs(cur + 1);
vis[i] = 0;
}
}
}
int main() {
int cnt = 0;
while(cin >> n){
memset(A,0,sizeof(A));
memset(p,0,sizeof(p));
memset(vis,0,sizeof(vis));
for(int i=0;i<n;i++) A[i] = i+1;
for(int i=2;i<n*2;i++) p[i] = is_prime(i);
if(cnt) cout<<endl;
printf("Case %d:\n",++cnt);
A[0] = 1;dfs(1);
}
return 0;
}
标签:dfs
原文地址:http://blog.csdn.net/iboxty/article/details/46129567