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.<br><br>Note: the number of first circle should always be 1.<br><br><img src=../../data/images/1016-1.gif><br>
Input
n (0 < n < 20).<br>
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.<br><br>You are to write a program that completes above process.<br><br>Print a blank line after each case.<br>
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
题意:素数环,但是开头都是1
需要预判段那个是素数
code:
#include<iostream>
#include<cmath>
#include<cstdio>
#include<cstring>
#include<cstdlib>
using namespace std;
int s[41];//储存数
bool p[41];//判断这个数是否使用过
bool tt[101];//判断是否是素数,提前判断
int n;
void dfs(int);//寻找
void prime();//判断素数
void print();//打印输出
int main()
{
prime();//预判
int tatal=0;
while(scanf("%d",&n)!=EOF)
{
++tatal;
memset(s,0,sizeof(s));
s[1]=1;//开始定为1
p[1]=true;//标记
cout<<"Case "<<tatal<<":"<<endl;
dfs(2);//从第二个数字开始寻找
cout<<endl;
}
return 0;
}
void prime()//判断素数的一种方法
{
tt[1]=true;
for(int i=2;i<=sqrt(100);++i)
if(!tt[i])
for(int j=2;j<=100/i;++j)
tt[j*i]=true;
}
void dfs(int step)
{
for(int i=2;i<=n;++i)
{
if(!p[i])
{
if(step<n&&!tt[i+s[step-1]])
{
s[step]=i;
p[i]=true;//标记
dfs(step+1);
//s[step]=0;
p[i]=false;//回溯
}
else if(step==n&&!tt[i+s[1]]&&!tt[i+s[step-1]])
//最后一个数需要同样与第一个数字判断
{
s[step]=i;
p[i]=true;//标记
print();
p[i]=false;//回溯
}
}
}
}
void print()
{
for(int i=1;i<n;++i)
{
cout<<s[i]<<" ";
}
cout<<s[n]<<endl;
}