1. Title Description: Click to open the link
2. Solving ideas: The problem is solved by backtracking. First, all primes in the 2*n range are generated to facilitate subsequent judgment. Next try to fill in each bit, if the number I satisfies is not used and it is the sum of the previous item is a prime, then it can be used, while marking it has been used, recursively looking for cur+1, exit when the use of the mark.
3. Code:
#define _crt_secure_no_warnings #include <iostream> #include <algorithm> #include <string> #include <sstream> #include <set> #include <vector> #include <stack> #include <map> #include < queue> #include <deque> #include <cstdlib> #include <cstdio> #include <cstring> #include < cmath> #include <ctime> #include <functional>using namespace std; #define N 20int vis[2*n],a[n],flag[n]; int n;void init ()//generates primes {int m = sqrt (2*n + 0.5), for (int i = 2; I <= m;i++) for (int j = i*i; J < 2 * N; j + = i) if (! VIS[J]) vis[j] = 1;} void dfs (int cur) {if (cur = = n&&!vis[a[0] + a[n-1]) {for (int i = 0; i < n; i++) printf ("%d%c", a[i], i = = N- 1? ' \ n ': ');} else for (int i = 2; I <= n;i++) if (!flag[i] &&!vis[i + a[cur-1]]) {a[cur] = i;flag[i] = 1;//set use flag DFS (cur + 1); Flag[i] = 0;//clear Use flag}}int main () {//freopen ("T.txt", "R", stdin), int rnd = 0;init (), while (~SCANF ("%d", &n)) {if (rn d) cout << endl;printf ("case %d:\n ", ++rnd); memset (A, 0, sizeof (a)); A[0] = 1;memset (flag, 0, sizeof (flag));d FS (1);} return 0;}
Example 7-4 Prime ring UVa524