http://acm.hdu.edu.cn/showproblem.php?pid=1016
素数结,简单dfs,只是前面的prime我开得太小,起先只开到21,可是题目算的是两数之和,最高可达38
#include<stdio.h> #include<string.h> int prime[40]={0,0,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}; int ans[21],vis[21],n; int print(int x) { int i; for(i=1;i<=x;i++) if(i==1) printf("%d",ans[i]); else printf(" %d",ans[i]); printf(" "); } int dfs(int x) { int i; if(x==n&&prime[ans[x]+ans[1]])//如果最后一个跟第一个加起来是素数,就输出 print(x); else { for(i=2;i<=n;i++) { if(prime[ans[x]+i] && !vis[i])//相邻 { ans[x+1]=i; vis[i]=1;//赋值进行深搜 dfs(x+1); vis[i]=0;//回溯后要赋为未访问状态 } } } } int main() { int t=1; while(~scanf("%d",&n)) { printf("Case %d: ",t++); memset(vis,0,sizeof(vis)); vis[1]=1; ans[1]=1; dfs(1); printf(" "); } return 0; }