Question: Place 1-N in a ring consecutively so that adjacent numbers are summed up as prime numbers and all results are output.
Analysis: Search + pruning. If you perform a bare search and use the dancing-links type to disassemble the linked list, the size of the list should be almost 16.
Here we use a property for pruning: adjacent numbers must be odd and odd numbers.
(If the above assumption is not true, there will be an odd or even number adjacent to them, then their sum must be an even number greater than 2, not a prime number)
According to the above assumption, there is another inference: only when n is an even number can there be a solution.
(N is an odd number, and there is always at least one odd number adjacent to each other. Same as above. Conflict (Pigeon nest principle ))
Therefore, the data for each search is actually n/2, and the time complexity is O (n/2 )! * 2 ^ (n/2 ));
Compress tables and query the output.
Note: The question is not mentioned, and each group of outputs has a blank line.
# Include <iostream> # include <cstdlib> # include <cstring> # include <cstdio> using namespace STD; int prime [32]; int visit [18]; int queue [18]; int size [18]; int ans [18] [100000] [18]; void DFS (int d, int N) {If (D = N &&! Prime [queue [D-1] + 1]) {for (INT I = 1; I <n; ++ I) ans [N] [size [N] [I] = queue [I]; Size [N] ++; return ;}for (INT I = D % 2 + 1; I <= N; I + = 2) if (! Visit [I] &! Prime [I + queue [D-1]) {visit [I] = 1; queue [d] = I; DFS (D + 1, n ); visit [I] = 0 ;}} int main () {memset (Prime, 0, sizeof (PRIME); prime [0] = prime [1] = 1; for (INT I = 2; I <32; ++ I) if (! Prime [I]) for (Int J = 2 * I; j <32; j + = I) prime [J] = 1; memset (visit, 0, sizeof (visit); visit [1] = 1; queue [0] = 1; memset (size, 0, sizeof (size); For (INT I = 2; I <= 16; I + = 2) DFS (1, I); int n, m, T = 0; while (~ Scanf ("% d", & N) {If (T ++) printf ("\ n"); printf ("case % d: \ n", t ); M = size [N]; for (INT I = 0; I <m; ++ I) {printf ("1"); For (Int J = 1; j <n; ++ J) printf ("% d", ANS [N] [I] [J]); printf ("\ n ");}} return 0 ;}