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
题意:给你一个数n,要输出一个环,要求为环的每一个相邻的2个数之和为素数。以1为环的起点,按逆时针方向排列,输出所有的可能!
思路:深度搜索!
AC代码
#include<stdio.h>
#include<string.h>
int flag[25],a[25],sumprim[25];
int n;
void makeprime(){ //打素数表
int ok;
memset(sumprim,0,sizeof(sumprim));
for(int i=2; i<=(n<<1); i++){
ok = 1;
for(int j=2; j*j<=i; j++) if(i % j == 0) ok = 0;
if(ok) sumprim[i] = 1;
}
}
void dfs(int cur)
{
if(cur==n&&sumprim[a[0]+a[n-1]]) //搜索树的树顶,还要判断第一个数与最后一个数的和
{
for(int i=0;i<n;i++){
if(i>0)printf(" ");
printf("%d",a[i]);
}
printf("\n");
}
else{
for(int i=2;i<=n;i++){
if(!flag[i]&&sumprim[i+a[cur-1]]) //i未使用并且与前一个数的和为素数
{
flag[i]=1; //标记使用
a[cur]=i; //将符合条件的i赋值给a数组
dfs(cur+1);
flag[i]=0;
}
}
}
}
int main()
{
int cas=0;
while(~scanf("%d",&n))
{
cas+=1;
printf("Case %d:\n",cas);
a[0]=1;
makeprime();
dfs(1);
printf("\n");
}
return 0;
}