Prime Ring ProblemTime Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 25134 Accepted Submission(s): 11222Problem DescriptionA ring is compose of n circles as shown in diagram. Put natural number 1, 2, ..., n into each circle separately, and the sum of numbers in two adjacent circles should be a prime.Note: the number of first circle should 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 above process.Print a blank line after each case. Sample Input68 Sample OutputCase 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
The question is to enclose numbers N, 1-N into a ring. Every two adjacent numbers in the ring are added as prime numbers, and all rings meeting the conditions are output. 1 is always the first number.
It feels like a deep search, so the water has passed ..
Code:
1 # include <stdio. h> 2 # include <iostream> 3 # include <string. h> 4 # include <algorithm> 5 # include <math. h> 6 # include <vector> 7 using namespace STD; 8 9 int used [20]; 10 int P [40]; 11 int N; 12 vector <int>; 13 int Kase; 14 void DFS (int K) 15 {16 if (k> = N) 17 {18 if (! P [A [0] + A [n-1]) // the first part of the array is connected to form a ring, and the first part is added as a prime number to satisfy the condition 19 {20 printf ("% d ", A [0]); 21 for (INT I = 1; I <. size (); I ++) 22 printf ("% d", a [I]); 23 printf ("\ n"); 24} 25 return; 26} 27 for (INT I = 2; I <= N; I ++) 28 {29 int B = A [. size ()-1]; 30 if (! Used [I] &! P [B + I]) 31 {32. push_back (I); 33 used [I] = 1; 34 DFS (k + 1); 35. pop_back (); 36 used [I] = 0; 37} 38} 39} 40 main () 41 {42 int I, j, k; 43 memset (p, 0, sizeof (p); 44 p [1] = 1; p [2] = 0; 45 for (I = 2; I <= 40; I ++) // evaluate the prime number 46 {47 for (j = 2; j * I <= 40; j ++) 48 p [J * I] = 1; 49} 50 Kase = 1; 51 while (scanf ("% d", & n) = 1) 52 {53 54 memset (used, 0, sizeof (used )); 55 used [1] = 1; 56. clear (); 57. push_back (1); 58 printf ("case % d: \ n", Kase ++); 59 DFS (1); 60 cout <Endl; 61} 62}