转载请注明出处:http://blog.csdn.net/a1dark
分析:直接DFS暴力搜索就行了、由于运行时间比较小就没去剪枝了、简单题不懂看代码
#include<stdio.h> #include<string.h> int map[25]; int vis[25]; int n,flag,cas; int judge(int x){ if(x%2==0)return 0; for(int i=2;i<=x/2;i++){ if(x%i==0) return 0; } return 1; } void dfs(int cur){ vis[1]=1; if(cur>n&&judge(map[n]+1)){ if(flag==0){ printf("Case %d:\n",cas);cas++; flag++; } for(int i=1;i<n;i++) printf("%d ",map[i]); printf("%d\n",map[n]); } else{ for(int i=2;i<=n;i++){ map[cur]=i; if(!vis[i]&&judge(map[cur]+map[cur-1])){ vis[i]=1; dfs(cur+1); vis[i]=0; } } } } int main(){ cas=1; while(scanf("%d",&n)!=EOF){ if(n==1){ printf("Case %d:\n",cas);cas++; printf("1\n");continue; } flag=0; memset(vis,0,sizeof(vis)); memset(map,0,sizeof(map)); map[1]=1; dfs(2); printf("\n"); } return 0; }