题意:给你一个N,要你把1->N这N个数组成一个环(第一个放的必须是1),要求是相邻的两个数加起来必须是素数( 素数环 ),而且最后一个和第一个同样要保持这个性质
思路: 记忆化搜索
Prime Ring Problem
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 18093 Accepted Submission(s): 8105
Problem Description
A 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.
Note: the number of first circle should 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 above process.
Print a blank line after each case.
You are to write a program that completes above 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
#include <stdio.h>
#include <algorithm>
#include <stdlib.h>
#include <string.h>
#include <math.h>
using namespace std;
int n,l;
int num[30];
bool visit[30];
bool flag; //标记是否找到正解
int judge( int x )
{
for( int i=2 ; i<sqrt( (double)x )+1 ; i++ )
if( x % i == 0 )
return false;
return true;
}
void DFS( int st , int count )
{
visit[st] = true;
if( count == n ){ //1到N全部放到了环里
if( judge( st + 1 ) ){
//printf("enter\n");
flag = true; //搜到了结果
}
return ;
}
for( int i=1 ; i<=n ; i++ ){
if( !visit[i] && judge( st + i ) ){
num[ count+1 ] = i;
//printf("%d\n",i);
DFS( i , count+1 );
if( flag ){
for( int j=1 ; j<=n ; j++ )
printf( j==n ? "%d\n" : "%d " , num[j] );
visit[i] = false;
flag = false;
}
else
visit[i] = false;
}
}
}
int main( )
{
int cas = 1;
while( scanf("%d",&n) == 1 ){
memset( visit , false , sizeof(visit) );
flag = false;
//l = 0;
printf("Case %d:\n",cas++);
num[1] = 1;
DFS( 1 , 1 );
printf("\n");
}
return 0;
}