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
这道题我是暴力解的,在一个环中相邻2个数字的和为素数,dfs一遍得出所有序列,进行判断,符合条件输出,不过要注意输出格式,每一组数的最后没有多余空格
C
#include <stdio.h>
#include <string.h>
#pragma warning(disable:4996)
int prime[40],res[20]={0,1},choose[20],N;
void get_prime(void) //(欧拉筛法)建立prime数组
{ //用别的方法也可以代替,让下标为素数的值为
int i,j,count,temp[40]; //0,例如prime[2],2为素数,prime[2]=0
for(i=2,count=0;i<40;i++) //6为合数,prime[6]=1
{
if(prime[2]==0)
temp[count++]=i;
for(j=0;j<count;j++)
{
if(i*temp[j]>=40)
break;
prime[i*temp[j]]=1;
if(temp[j]%i==0)
break;
}
}
}
void print(void)
{
int i;
for(i=1;i<=N;i++)
printf(i==N?"%d\n":"%d ",res[i]); //这一句prinf是从别人那里学来的。从来没想过printf能这么用
}
void dfs(int x)
{
int i;
if(x==N) //符合条件进行判断
{
if(prime[1+res[N]]==0) //判断最后一项与第一项之和是否为素数
print(); //是素数就输出
return;
}
for(i=2;i<=N;i++) //枚举
{
if(choose[i]==0&&prime[res[x]+i]==0)
{
choose[i]=1;
res[x+1]=i;
dfs(x+1);
choose[i]=0;
}
}
}
int main(void)
{
int test=0;
get_prime();
while(scanf("%d",&N)!=EOF)
{
printf("Case %d:\n",++test);;
if(N==1)
printf("1\n");
else if(N%2)
;
else
dfs(1);
putchar('\n');
}
return 0;
}