Http://acm.nyist.net/JudgeOnline/problem.php? PID = 1, 488
Recursive solving is actually a deep search and full Sorting Problem.
Classic Prime Number Problem. Note that 1 forms a prime ring.
Import Java. util. extends; public class main {public static void main (string... ARGs) {// base number table for (INT I = 1; I <40; I ++) {ISP [I] = isprime (I) ;}while (CIN. hasnext () {n = cin. nextint (); If (n = 0) break; If (n = 1) {// 1 forms the self-ring system. out. println ("case" + Count ++ ": \ N1"); continue;} If (N % 2 = 1) {// if n is an odd number, the system is undefined. out. println ("case" + Count ++ ":"); system. out. println ("No answer"); continue;} A = new int [n + 1]; A [1] = 1; // the first one is 1system. Out. println ("case" + Count ++ ":"); DFS (2); If (! Hasres) system. out. println ("No answer"); hasres = false ;}} public static void DFS (INT cur) {If (cur = n + 1 & ISP [A [1] + A [n]) {for (INT I = 1; I <= N; I ++) {system. out. print (A [I] + "");} system. out. println (); hasres = true;} else {for (INT I = 2; I <= N; I ++) {// try to place each number of IIF (! Visit [I] & ISP [A [cur-1] + I]) {A [cur] = I; visit [I] = true; DFS (cur + 1 ); visit [I] = false ;}}} public static Boolean isprime (int n) {for (INT I = 2; I <= n/2; I ++) {If (N % I = 0) return false;} return true;} static int [] A; static Boolean [] ISP = new Boolean [40]; static int N, count = 1; static Boolean [] visit = new Boolean [20]; static sort CIN = new sort (system. in); static Boolean hasres = false ;}
This question can be easily transformed from a full Sorting Problem to a full Sorting Problem.CodeAs follows:
Import Java. util. extends; public class main {public static void main (string... ARGs) {While (CIN. hasnext () {n = cin. nextint (); If (n = 0) break; A = new int [n + 1]; system. out. println ("case" + Count ++ ":"); DFS (1) ;}} public static void DFS (INT cur) {If (cur = n + 1) {for (INT I = 1; I <= N; I ++) {system. out. print (A [I] + "");} system. out. println () ;}else {for (INT I = 1; I <= N; I ++) {// try to place each number of IIF (! Visit [I]) {A [cur] = I; visit [I] = true; DFS (cur + 1); visit [I] = false ;}}}} static int [] A; static int N, Count = 1; static Boolean [] visit = new Boolean [20]; static expect CIN = new expect (system. in );}