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 4Case 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.
利用回溯法,见紫皮书194页例题
代码
#include<iostream>
#include<string.h>
#include<math.h>
using namespace std;
int a[20],vis[20];
int n;
int isp(int x) //判断是否为素数
{
int i;
if(x<2)
return 0;
for(i=2;i<=sqrt(x);i++)
{
if(x%i==0)
return 0;
}
return 1;
}
void dfs(int s)//深搜
{
int i;
if(s==n&&isp(a[0]+a[n-1]))// 递归边界,测试第一个数和最后一个数
{
for(i=0;i<n-1;i++)
cout<<a[i]<<" ";
cout<<a[n-1]<<endl;
}
else
{
for(i=2;i<=n;i++)
{
if(!vis[i]&&isp(i+a[s-1]))//如果i没有用过,并且与前一个数之和为素数
{
a[s]=i;
vis[i]=1;//设置使用标记
dfs(s+1);
vis[i]=0;//清除标记
}
}
}
}
int main()
{
int t=1;
while(cin>>n)
{
memset(vis,0,sizeof(vis));
a[0]=1;
cout<<"Case "<<t++<<":"<<endl;
dfs(1);
cout<<endl;
}
return 0;
}