Prime Ring Problem
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission (s): 20489 Accepted Submission (s): 9159
Problem Description
A 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.
Input
N (0 <n <20 ).
Output
The 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
6
8
Sample Output
Case 1:
1 4 3 2 5 6
1 6 5 2 3 4
Case 2:
1 2 3 8 5 6 7 4
1 2 5 8 3 4 7 6
1 4 7 6 5 8 3 2
1 6 7 4 3 8 5 2
Judge whether the sum of two adjacent numbers 1-N is a prime number, and output a prime ring.
DFS Algorithm
Import java. io. *; import java. util. *; public class Main {public static int n; public static boolean mark []; public static int a []; public static PrintWriter pw; public static void main (String [] args) {consumer SC = new consumer (new BufferedInputStream (System. in); // enter pw = new PrintWriter (new BufferedOutputStream (System. out), true); // output int number = 1; while (SC. hasNextInt () {n = SC. nextInt (); mark = new boolean [n + 1]; a = ne W int [n + 1]; mark [1] = true; a [0] = 1; pw. println ("Case" + number ++ ":"); DFS (1); pw. println () ;}} public static void DFS (int len) {if (len = n) {// determine whether the first element and the last element are prime numbers. if (isPrime (a [0] + a [n-1]) {for (int I = 0; I <n-1; I ++) {pw. print (a [I] + "");} pw. println (a [n-1]);} return;} for (int I = 2; I <= n; I ++) {if (! Mark [I] & isPrime (a [len-1] + I) {// determine whether two adjacent elements are prime numbers mark [I] = true; a [len] = I; DFS (len + 1); mark [I] = false; // backtracking }}// determine if the prime number is public static boolean isPrime (int m) {for (int I = 2; I <= Math. sqrt (m); I ++) {if (m % I = 0) return false;} return true ;}}