Problem descriptionA ring is compose of N circles as shown in digoal. put Natural Number 1, 2 ,..., N into each circle separately, and the sum of numbers in two adjacent circles shoshould be a prime.
Note: The number of First Circle shoshould always be 1.InputN (0 <n <20 ).
OutputThe output format is shown as sample below. each row represents a series of circle numbers in the ring beginning from 1 clockwisely and anticlockwisely. the order of numbers must satisfy the above requirements. print solutions in lexicographical order.
You are to write a program that completes abve process.
Print a blank line after each case.Sample Input
68
Sample output
Case 1:1 4 3 2 5 61 6 5 2 3 4Case 2:1 2 3 8 5 6 7 41 2 5 8 3 4 7 61 4 7 6 5 8 3 21 6 7 4 3 8 5 2
// Backtracking (DFS traversal solution tree) # include <iostream> using namespace STD; int N, CNT = 1; int vis [21], a [21]; // prime number table to accelerate subsequent judgment of int primelist [38] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}; void DFS (INT cur) {If (cur = N & primelist [A [0] + A [n-1]) // recursive boundary, do not forget to test the first and last number {cout <A [0]; for (INT I = 1; I <n; ++ I) cout <"" <A [I]; // print format of the question. Note that the last digit is printed without a space. cout <Endl ;} else For (INT I = 2; I <= N; + + I) // try to place each number IIF (! Vis [I] & primelist [I + A [cur-1]) // if u has not been used, and the sum of the preceding number is a prime number {A [cur] = I; // put the number in a vis [I] = 1; // set the use flag DFS (cur + 1); // recursively call vis [I] = 0; // remember to change the flag back to clear the flag !}} Int main () {A [0] = 1; // The position of 1 remains unchanged while (CIN> N) {memset (VIS, 0, sizeof (VIS )); // tag the array to clear cout <"case" <CNT ++ <":/N"; DFS (1); cout <Endl ;}return 0 ;}