# Prime Ring Problem

Prime Ring Problem

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. n (0 < n < 20).

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.

The followings are programmed codes. Your task is to complete function dfs(). When you submit your program, you just submit only function dfs(). The rest of program will be added to your program automatically.

//The following codes will become the front of your program automatically.
#include<stdio.h>
#include<string.h>
int n,ans,isprime[]= {0,0,1,1,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,0,0,0,0,1,0,1,0,0,0,0,0,1,0,0,0},vis;

//The code you must submit
void dfs(int step)
{
...
}

//The following codes will become the rear of your program automatically.
int main()
{
int count;
count=0;
while(scanf("%d",&n)!=EOF)
{
count++;
ans=1;
memset(vis,0,sizeof(vis));
printf("Case %d:\n",count);
dfs(2);
printf("\n");
}
return 0;
}

``````6
8``````

``````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<string.h>
int n,ans,isprime[]= {0,0,1,1,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,0,0,0,0,1,0,1,0,0,0,0,0,1,0,0,0},vis;
//The code you must submit
void dfs(int step)
{
int i;
if(step>n)
{
for(i=1;i<n;i++)
printf("%d ",ans[i]);
printf("%d\n",ans[n]);
return ;
}
for(i=2;i<=n;i++)
{
if(vis[i])
continue;
if(isprime[ans[step-1]+i]==0)
continue;
if(step==n&&isprime[i+1]==0)
continue;
ans[step]=i;
vis[i]=1;
dfs(step+1);
vis[i]=0;
}

}

//The followingcodes will become the rear of your program automatically.
int main()
{
int count;
count=0;
while(scanf("%d",&n)!=EOF)
{
count++;
ans=1;
memset(vis,0,sizeof(vis));
printf("Case %d:\n",count);
vis=1;
dfs(2);
printf("\n");
}
return 0;
}
``````

``````
#include<stdio.h>
#include<string.h>
int n,ans,isprime[]={0,0,1,1,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,0,0,0,0,1,0,1,0,0,0,0,0,1,0,0,0},vis;
void dfs(int step)
{
int i;
if(step==n+1)
{
if(isprime[ans[n]+1])
for(i=1;i<=n;i++)
printf("%d%c",ans[i],i==n?'\n':' ');
}
else
for(i=2;i<=n;i++)
if(!vis[i]&&isprime[i+ans[step-1]])
{
ans[step]=i;
vis[i]=1;
dfs(step+1);
vis[i]=0;
}
}
int main()
{
int count;
count=0;
while(scanf("%d",&n)!=EOF)
{
count++;
ans=1;
memset(vis,0,sizeof(vis));
printf("Case %d:\n",count);
dfs(2);
printf("\n");
}
return 0;
}
``````