这道题出现的最大问题是超时,后来参照网上的代码才明白原因:
按照自己的思想,先判断数字是否重复,此过程经历一系列递归,然后又在这些不重复的序列循环搜索素数序列,这样就经历了两回循环,必然耗时,而进行优化后,可以在递归过程用两个条件判断,既要求数字不重复,又要求相邻和两端必须是素数!大大减少了运行时间!
Prime Ring Problem
Time Limit : 4000/2000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 24 Accepted Submission(s) : 7
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.
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
AC码
#include <cstdio>
#include <cstring>
int n,m,a[21],arr[21]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20},mark[21];
int c[50];
int k=1,j;
void dfs(int v)
{
if(v==n&&c[a[0]+a[n-1]])
{
for(int r=0;r<n;r++)
{
if(!r)printf("%d",a[r]);
else printf(" %d",a[r]);
}
printf("\n");
return;
}
/*if(v >= n){
for(int i=1;i<n;i++) //这种方法超时
{
if(!c[a[i]+a[i-1]])
return;
if(!c[a[0]+a[n-1]])
return;
}
if(a[0]==1)
{
for(int i = 0;i < n;i++)
{
printf("%d ",a[i]);
}
printf("\n");
return ;
}*/
for(int j = 1; j< n;j++)
{
if(!mark[j]) //打印出来的数字不能重复
{
if(c[a[v-1]+arr[j]]) //同时判断必须是素数
{
mark[j] = 1; //标记为已用过
a[v] = arr[j];
dfs(v+1);
mark[j] = 0; //如果退回来一步就必须把原位置标记为没用过
}
else continue;
}
}
}
int main()
{
while(scanf("%d",&n)==1)
{
memset(mark,0,sizeof(mark));
c[2]=c[3]=c[5]=c[7]=c[11]=c[13]=c[17]=c[19]=c[23]=c[29]=c[31]=c[37]=c[39]=1;
printf("Case %d:\n",k++) ;
a[0]=1;//因为a[0]已经确定,直接写出来可以节省判断的时间
dfs(1); //a[0]已经打印,从第二位开始判断
printf("\n");
}
}