# Prime Ring Problem

##### Total Submission(s) : 13   Accepted Submission(s) : 9

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.

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

Source

Asia 1996, Shanghai (Mainland China)

a[25]存放的是1-25，作为排列用；

flag[25]标记有哪些数还未被使用，dfs之前令flag[j]=1,dfs之后回溯令flag[j]=0;

flag[j]=1;
DFS(i+1);
flag[j]=0;

#include<cstdio>
#include<memory>
using namespace std;
int a[25],flag[25],ans[25],c[50];
int n;
void DFS(int i)
{
if(i==n&&c[ans[0]+ans[n-1]])
{
for(int k=0;k<n;k++)
{
if(!k)printf("%d",ans[k]);
else printf(" %d",ans[k]);
}
printf("\n");
return ;
}
for(int j=1;j<n;j++)
{
if(!flag[j])
{
if(c[ans[i-1]+a[j]])
{
ans[i]=a[j];flag[j]=1;
DFS(i+1);
flag[j]=0;
}
else continue;
}
}

}
int main()
{
int i,j,t=1;
for(i=0;i<25;i++) a[i]=i+1;
memset(c,0,sizeof(c));
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;
ans[0]=1;
while(scanf("%d",&n)!=EOF)
{
memset(flag,0,sizeof(flag));
printf("Case %d:\n",t++);
DFS(1);
printf("\n");
}
return 0;
}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120