Idea: The first number filled 1, after each number to judge the number and the previous number to add whether it is a prime, is filled, and then marked, near one-step recursive solution. Then remember to backtrack and continue to judge the sum of the next and previous numbers as the number of primes.
/*HDU 1016 Prime Ring Problem---classic DFS*/#include<cstdio>#include<cstring>intN;BOOLprimer[ $], visit[ -];//Primer The Prime number table, visit mark whether to accessinta[ -];//array A stores the number of placements/*40 within the prime number of the table*/voidGetprimer () {//because n Max is 20, so just hit theprimer[0] = primer[1] =1;//1 means not a prime number for(inti =2; I <7; ++i) { for(intj = i*i; J < +; j+=i) {Primer[j]=1;//1 means not a prime number}//For (j)}//For (i)}/*DFS Search num is the number of filled numbers*/voidDfsintnum) { inti; //All completed and the sum of the first is the prime number output if(num = n &&!primer[a[num-1] + a[0]]){ for(i =0; I < num-1; ++i) {printf ("%d", A[i]); } printf ("%d\n", A[i]); return; } Else{ for(i =2; I <= N; ++i) { //the number has not been used and the sum of the previous number is prime if(!visit[i] &&!primer[a[num-1] +i]) {A[num]=i; Visit[i]=1; DFS (Num+1);//Recursive fill numberVisit[i] =0;//Backtracking } } }}intMain () {intKase =0; Getprimer (); while(SCANF ("%d", &n) = =1) {memset (visit,0,sizeofvisit); printf ("Case %d:\n", ++Kase); visit[1] =1;//1 used.a[0] =1;//the first number is 1 .Dfs1); printf ("\ n"); } return 0;}View Code
HDU 1016 Prime Ring problem---classic DFS