Prime Ring problem
Time limit:4000/2000 MS (java/others) Memory limit:65536/32768 K (java/others)Total submission (s): 40339 Accepted Submission (s): 17813
problem 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 the adjacent circles should is a PR Ime.
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 is to write a program, that completes above process.
Print a blank line after each case.
Sample Input
68
Sample Output
Case 1:1 4 3 2 5 a 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 title means that each number of 1 to n constitutes a ring, and the sum of the two adjacent numbers is the prime number, and the results of the match are all output in the dictionary order; The method uses DFS, and each number is traversed to find the matching situation;
#include <iostream> #include <cstring> #include <cstdio> #include <cmath> #include <string > #include <algorithm> #include <queue>using namespace Std;int n;int a[25];//save result int flag[25];// Record whether a number has been used for bool IsPrime (int n) {if (n = = 1 | | n = = 0) return 0;if (n = = 2) return 1;for (int i = 2; I <= sqrt ((double) n); I + +) {if (n%i = = 0) return 0;} return 1;} void dfs (int tot) {if (tot = = n-1) {if (IsPrime (a[n-1] + a[0]) {int o = 0;for (int i = 0; i < n; i++) {while (o++) {print F (""); break;} printf ("%d", A[i]);} printf ("\ n");} return;} for (int i = 2; I <= n; i++) {if (flag[i] = = 0) {if (IsPrime (A[tot] + i) {Flag[i] = 1;a[tot + 1] = I;dfs (tot + 1); Flag[i] = 0;}}} int main () {int k = 1;while (~scanf ("%d", &n)) {printf ("Case%d:\n", k++), a[0] = 1;memset (flag, 0, sizeof (flag));d FS (0); printf ("\ n");} return 0;}
Prime Ring problem-hdu1016 (DFS)