Question link: http://acm.nyist.net/JudgeOnline/problem.php? PID = 1, 488
There is an integer N, which sorts the numbers from 1 to n into loops without repetition. The sum of every two adjacent numbers (including the first and last) is a prime number, which is called a prime ring.
For simplicity, we specify that each Prime Ring starts from 1. For example, it is a prime ring of 6.
-
Input
-
There are multiple groups of test data, each group input a n (0 <n <20), n = 0 indicates that the input ends.
-
Output
-
The first row of each group outputs the corresponding case sequence number, starting from 1.
If there is a prime number ring that satisfies the meaning of the question, it is output from small to large.
Otherwise, no answer is output.
-
Sample Input
-
6830
-
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 2Case 3:No Answer
Train of Thought Analysis:
If we use a full arrangement to determine one by one, it will be TLD, so here we adopt the Backtracking Strategy. Here there is a trap, that is, the self-ring, such as 1, to construct the self-ring, and 2 is a prime number, so 1 is true.
1. Determination of prime numbers
A: As the test data is smaller than 20, we can use enumeration to determine the prime number.
2. Use of backtracking
A. Mark the array and change the status during backtracking.
AC code
//// Scanf printf reduces the time ..
# Include <iostream>
# Include <stdio. h>
# Include <algorithm>
# Include <string>
# Include <cstring>
Using namespace STD;
Int A [21];
Int N;
Bool visited [21];
Bool isprimer (int n)
{
If (n = 2 | n = 3 | n = 5 | n = 7 | n = 11 | n = 13 | n = = 17 | n = 19 | n = 23 | n = 29 | n = 31 | n = 37)
Return true;
Return false;
}
Int COUNT = 0;
Bool DFS (INT cur)
{
If (cur = N)
{
If (n = 1) {If (isprimer (A [0]) printf ("% d \ n", a [0]); else return false ;}
Else if (isprimer (A [0] + A [n-1])
{
For (INT I = 0; I <n; I ++)
Printf ("% d", a [I]);
Printf ("\ n ");
Return true;
}
}
Else if (cur! = N)
{
Int I, J;
For (I = 2; I <= N; I ++)
{
If (! Visited [I] & isprimer (I + A [cur-1])
{
A [cur] = I;
Visited [I] = true;
DFS (cur + 1 );
Visited [I] = false; // backtracking
}
}
}
}
Int main ()
{
Int I;
While (scanf ("% d", & N), n)
{
Memset (A, 0, sizeof ());
For (I = 0; I <n; I ++) A [I] = I + 1;
Memset (visited, false, sizeof (visited ));
Visited [1] = true;
Count ++;
Printf ("case % d: \ n", count );
If (n = 1) {printf ("% d \ n", a [0]); continue;} // self-ring Condition
If (N % 2! = 0) {printf ("No answer \ n"); continue;} // if n is an odd number, there is an even number not equal to 2, not a prime number, which can be directly excluded
DFS (1); // small data volume. You can determine that the first priority must be 1.
}
// System ("pause ");
Return 0;
}