标签:
6 8
Case 1: 1 4 3 2 5 6 1 6 5 2 3 4 Case 2: 1 2 3 8 5 6 7 4 1 2 5 8 3 4 7 6 1 4 7 6 5 8 3 2 1 6 7 4 3 8 5 2
#include<iostream> #include<cstring> #include<cstdio> #include<cmath> #include<string> #include<algorithm> #include<queue> using namespace std; int n; int a[25];//保存结果 int flag[25];//记录一个数是否已用过 bool isprime(int n) { if (n == 1 || n == 0) return 0; if (n == 2) return 1; for (int i = 2; i <= sqrt((double)n); i++) { if (n%i == 0) return 0; } return 1; } void dfs(int tot) { if (tot == n-1) { if (isprime(a[n - 1] + a[0])) { int o = 0; for (int i = 0; i < n; i++) { while (o++) { printf(" "); break; } printf("%d", a[i]); } printf("\n"); } return; } for (int i = 2; i <= n; i++) { if (flag[i] == 0) { if (isprime(a[tot] + i)) { flag[i] = 1; a[tot + 1] = i; dfs(tot + 1); flag[i] = 0; } } } } int main() { int k = 1; while (~scanf("%d", &n)) { printf("Case %d:\n", k++); a[0] = 1; memset(flag, 0, sizeof(flag)); dfs(0); printf("\n"); } return 0; }
Prime Ring Problem—hdu1016(DFS)
标签:
原文地址:http://blog.csdn.net/jelly_acm/article/details/51331381