题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1016
#include <iostream> #include <string.h> using namespace std; /**************************************************************************************************************** 题意:输出满足相邻的相加是素数的序列 思路: 1,很清晰,要用dfs,刚开始想复杂了,可能最近都在用回溯,就用回溯了,然后就傻逼了 2,利用打素数表能优化时间 3,千万别忘了将最后一个数和 1 要进行比较 ****************************************************************************************************************/ int N; int visit[20+5]; int f[20+5]; int fuc[40]={0,1,1,1,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,0,0,0,0,1,0,1,0,0,0,0,0,1,0,0}; void dfs(int num) { if(num == N && fuc[f[num-1]+1]){ for(int i = 0;i < num;i ++){ if(i == 0) cout<<f[i]; else cout<<" "<<f[i]; } cout<<endl; } for(int i = 2;i <= N;i ++){ if(visit[i]) continue; if(fuc[i+f[num-1]]){ visit[i]=1; f[num]=i; dfs(num+1); visit[i]=0; } } } int main() { int num=1; while(cin>>N) { if(N<=0 || N>= 20) break; cout<<"Case "<<num<<":"<<endl; num++; memset(visit,0,sizeof(visit)); f[0]=1; dfs(1); cout<<endl; } return 0; }