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开始相邻两个数必须是素数
解题:可以先打个素数表 然后用深搜 代码给详解
#include <iostream>
#include <cstring>
using namespace std;
int isprime[38] = {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}; //素数表
int a[25];
bool vis[25]; //表示数用过没
int n;
void dfs(int num) //深搜
{
if(num==n&&isprime[a[0]+a[n-1]]) //num 为搜索符合数的个数 往下看就知道了 里面那个是1和最后一个数相加
{
cout<<a[0];
for(int i=1; i<n; i++)
{
cout<<" "<<a[i];
}
cout<<endl;
}
else
{
for(int i=2; i<=n; i++)
{
if(!vis[i]&&isprime[a[num-1]+i]) //这种情况从1开始搜 如果没用过相加是个素数 符合情况
{
a[num]=i; //储存这个数进行下次判断
vis[i]=1; //表示这个数用过了
dfs(num+1);
vis[i]=0; //一种情况完成后就要归零 表示没用过
}
}
}
}
int main()
{
int ans=1;
a[0]=1;
while(cin>>n)
{
memset(vis,0,sizeof(vis)); //保存零 表示都没用过
cout<<"Case "<<ans++<<":"<<endl;
dfs(1); //从1开始搜
cout<<endl;
}
return 0;
}
#include <cstring>
using namespace std;
int isprime[38] = {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}; //素数表
int a[25];
bool vis[25]; //表示数用过没
int n;
void dfs(int num) //深搜
{
if(num==n&&isprime[a[0]+a[n-1]]) //num 为搜索符合数的个数 往下看就知道了 里面那个是1和最后一个数相加
{
cout<<a[0];
for(int i=1; i<n; i++)
{
cout<<" "<<a[i];
}
cout<<endl;
}
else
{
for(int i=2; i<=n; i++)
{
if(!vis[i]&&isprime[a[num-1]+i]) //这种情况从1开始搜 如果没用过相加是个素数 符合情况
{
a[num]=i; //储存这个数进行下次判断
vis[i]=1; //表示这个数用过了
dfs(num+1);
vis[i]=0; //一种情况完成后就要归零 表示没用过
}
}
}
}
int main()
{
int ans=1;
a[0]=1;
while(cin>>n)
{
memset(vis,0,sizeof(vis)); //保存零 表示都没用过
cout<<"Case "<<ans++<<":"<<endl;
dfs(1); //从1开始搜
cout<<endl;
}
return 0;
}