题目:
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.
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.
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之间的数字(包括1和n)进行排序,但数字1的位置是固定的,所有数字排序成为一个环时必须满足条件:相邻两数相加之和必须为素数,且排序的任意数字只能出现一次。
代码如下:
#include<iostream>
using namespace std;
int sushu[40]={0,0,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};//素数为1
int n,s[20],mark[20];
int dfs(int a)
{
if(a==n && sushu[s[a]+1])//首尾两数之和为素数
{
for(int i=1;i<n;i++)
cout<<s[i]<<" ";
cout<<s[n]<<endl;
}
else
{
for(int i=2;i<=n;i++)
{
if(sushu[s[a]+i] && mark[i]==0)
{
mark[i]=1;//进行标记
s[a+1]=i;//确定下个位置的数字
dfs(a+1);//根据数组下标(从第n个数)进行搜索
mark[i]=0;// 回溯,撤消访问标志
}
}
}
return 0;
}
int main()
{
int k;
k=s[1]=1;
while(cin>>n)
{
cout<<"Case "<<k++<<":"<<endl;
memset(mark,0,sizeof(mark));
dfs(1);//根据第一个数1进行搜索
cout<<endl;
}
return 0;
}
这个题目用数组枚举出所属范围内的所有数字之和的情况,是素数则为1,否则为0,为了避免出现重复的数字可以用mark数组进行标记,详细解释请看代码中的注释