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
分析:
意思是给你一个数n,要构成一个素数环,这个素数由1-n组成,它的特征是选中环上的任意一个数字i,i与它相连的两个数加起来都分别为素数,满足就输出
要全部搜索,所以用dfs,要判断是否是素数,并且看到数据最大是40.打表把1到40判断素数的结果存在数组里就最简单啦,而且高效
而素数打表有四种方法详见我另一篇博客
https://blog.youkuaiyun.com/qq_42079027/article/details/81410361
#include<stdio.h>
#include<string.h>
int prime[40]={0,1,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};//素数打表,因为n最大是20,所以只要打到40
int n;
int book[21],a[21];
void dfs(int num)//深搜
{
int i;
if(num==n&&prime[a[num-1]+a[0]]) //满足条件了,就输出来
{
for(i=0;i<num-1;i++)
printf("%d ",a[i]);
printf("%d\n",a[num-1]);
}
else
{
for(i=2;i<=n;i++)
{
if(book[i]==0&&prime[i+a[num-1]])//如果未被标记,且是素数
{
book[i]=1;//标记了
a[num]=i;//放进数组
dfs(num+1); //递归调用
book[i]=0; //退去标记
}
}
}
}
int main()
{
int id=0;
while(scanf("%d",&n)!=EOF)
{
id++;
printf("Case %d:\n",id);
memset(book,0,sizeof(book));
a[0]=1;
dfs(1);
printf("\n");
}
return 0;
}