Prime RingProblem素环问题
Problem Description
A ring is composeof n circles as shown in diagram. Put natural number 1, 2, ..., n into eachcircle separately, and the sum of numbers in two adjacent circles should be aprime.
Note: the number of first circle should always be 1.
环是组合成n个圆圈所示的图。把自然数1,2,...,n为进分别各圈,和数字中的两个相邻圈之和应该是一个素数。
注意:第一圈的数量始终应为1。
Input
n (0 < n <20).
Output
The output formatis shown as sample below. Each row represents a series of circle numbers in thering beginning from 1 clockwisely and anticlockwisely. The order of numbersmust 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.
输出格式如下图所示的样品。每一行代表一个系列的圆形数字的环从1开始顺时针和按逆时针方向。号的顺序,必须满足上述要求。在字典顺序打印解决方案。
请你写一个程序,完成上述过程。
打印每个案例后,一个空行。
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<math.h>
#include<string.h>
int nums[10001];
int vis[10001];
int n;
int isPrime(int num)
{
if(num==1||num==0)
return 0;
for(int i=2;i<=num/2;i++)
{
if(num%i==0)
{
// printf("xxx");
return 0;
}
}
return 1;
}
void dfs(int step)
{
if(step==n+1)
{
int j;
for(j=1;j<n;j++)
printf("%d ",nums[j]);
printf("%d",nums[j]);
printf("\n");
return;
}
for(int i=1;i<=n;i++)
{
if(vis[i])continue;
if(isPrime(nums[step-1]+i))
{
if(step==n)
{
//printf("%d\n",i+1);
if(!isPrime(i+1))
continue;
}
nums[step]=i;
vis[i]=1;
dfs(step+1);
vis[i]=0;
}
}
}
int main()
{
int cnt=1;
while(scanf("%d",&n)!=EOF)
{
memset(vis,0,sizeof(vis));
memset(nums,0,sizeof(nums));
nums[1]=1;
vis[1]=1;
printf("Case %d:\n",cnt++);
dfs(2);
printf("\n");
}
return 0;
}