HDU

来源:互联网 发布:淘宝主图尺寸750 编辑:程序博客网 时间:2024/06/16 18:37

       思路:经典dfs问题,注意1和最后一个数的和也必须是质数。对于n是奇数的情况,根本不会有结果,因为必定会有两个奇数相邻,他们的和是大于2的偶数就不可能是质数。

AC代码

#include <cstdio>#include <cmath>#include <algorithm>#include <cstring>#include <utility>#include <string>#include <iostream>#include <map>#include <set>#include <vector>#include <queue>#include <stack>using namespace std;#pragma comment(linker, "/STACK:1024000000,1024000000") #define eps 1e-10#define inf 0x3f3f3f3f#define PI pair<int, int> typedef long long LL;const int maxn = 20 + 5;int vis[maxn], ans[maxn], d[maxn], n;void init(int n) {int m = sqrt(n+0.5);memset(vis, 0, sizeof(vis));for(int i = 2; i <= m; ++i) if(!vis[i])for(int j = i*i; j <= n; j+=i) vis[j] = 1;}void dfs(int cnt) {if(cnt == n) {if(!vis[ans[n-1]+1]) for(int i = 0; i < n; ++i) {if(i==n-1) printf("%d\n", ans[i]);else printf("%d ", ans[i]);}return;}for(int i = 2; i <= n; ++i) {if(!d[i] && !vis[ans[cnt-1]+i]) {d[i] = 1;ans[cnt] = i;dfs(cnt+1);d[i] = 0;}}}int main() {init(22);int kase = 0;while(scanf("%d", &n) == 1) {memset(d, 0, sizeof(d));printf("Case %d:\n", ++kase);ans[0] = 1;d[1] = 1;dfs(1);printf("\n");}return 0;} 

如有不当之处欢迎指出!

0 0
原创粉丝点击