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.
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 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
题意:很容易理解,就是让你输出满足相邻的相加是素数的序列(注意不要重复)
解题思路:用DFS去遍历它,然后判断是否满足。
#include <stdio.h>
int a[20],b[20],n;
int judge(int m)
{ int k;
if(m == 2)
return 1;
for(k = 2; k < m; k++)
{
if(m%k == 0)
{
break;
}
}
if(k == m)
return 1;
else
return 0;
}
void dfs(int j)
{
int i;
if(j == n && judge(a[n]+1))
{
for(i = 1;i<n;i++)
printf("%d ",a[i]);
printf("%d\n",a[n]);
}
for(i = 2;i<=n;i++)
{
if(b[i]!=0 && judge(a[j]+i))
{
a[j+1]=i;
b[i]=0;
dfs(j+1);
b[i]=i;
}
}
}
int main()
{
int k;
a[1]=1;
for(k=1;k<=20;k++)
b[k]=k;
for(k=1;scanf("%d",&n)!=EOF;k++)
{
printf("Case %d:\n",k);
if(n%2 == 0)
dfs(1);
printf("\n");
}
return 0;
}