题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1016
------------------------------------------------------------------------------------
题意:n个数,要求相邻的两个数之和为素数。
思路:DFS,深搜思想,把每种情况便利一遍。
代码:
#include<cstdio> #include<cstring> #include<algorithm> #include<iostream> #include<string> #include<vector> #include<stack> #include<bitset> #include<cstdlib> #include<cmath> #include<set> #include<list> #include<deque> #include<map> #include<queue> using namespace std; typedef long long ll; const double PI = acos(-1.0); const double eps = 1e-6; int n,cnt = 1; int vis[21],A[21]; int isp[38] = {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}; void dfs(int cur) { if(cur == n && isp[A[0] + A[n-1]]){ printf("%d",A[0]); for(int i = 1;i < n;i++) printf(" %d",A[i]); printf("\n"); }else for(int i = 2;i <= n;++i) if(!vis[i] && isp[i + A[cur-1]]){ A[cur] = i; vis[i] = 1; dfs(cur + 1); vis[i] = 0; } } int main() { A[0] = 1; while(~scanf("%d",&n)) { for(int i=0;i<21;i++) vis[i]=0; printf("Case %d:\n",cnt++); dfs(1); printf("\n"); } return 0; }