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
代码:
#include
#include
#include
using namespace std;
const int maxn=105;
bool pri[maxn];
int n;
int vis[maxn];
int ans[maxn];
void getPrime()
{
memset(pri,true,sizeof(pri));
for(int i=2;i<=maxn;i++)
{
for(int j=2;j<=sqrt(i);j++)
{
if(i%j==0)
{
pri[i]=false;
break;
}
}
}
pri[0]=pri[1]=false;
}
void dfs(int x)
{
if(x>n)return;
if(x==1)
{
ans[1]=1;
for(int i=2;i<=n;i++)
if(pri[i+1]&&!vis[i])
{
vis[i]=1;
ans[x+1]=i;
dfs(x+1);
vis[i]=0;
}
}
else if(x==n)
{
if(!pri[ans[x]+1])
return;
else
{
printf("%d",ans[1]);
for(int i=2;i<=n;i++)
printf(" %d",ans[i]);
printf("\n");
return;
}
}
else
{
for(int j=2;j<=n;j++)
{
if(pri[j+ans[x]]&&!vis[j])
{
ans[x+1]=j;
vis[j]=1;
dfs(x+1);
vis[j]=0;
}
}
}
}
int main()
{
getPrime();
int k=1;
while(~scanf("%d",&n))
{
if(n<=0||n>=20)break;
memset(vis,0,sizeof(vis));
printf("Case %d:\n",k);
if(n%2!=1)dfs(1);
k++;
printf("\n");
}
return 0;
}