题目描述:
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
思路分析:
搜索题,首先用筛法求素数得到所有40以下的素数并记录在prime数组里,prime[i]=1,表示i为素数。然后搜索找到列举所有可能的情况,判断前后两者之间相加是否为
素数。每访问一个数,用数组z记录访问标记,令z[i]=1;dfs后令z[i]=0,以便接下来的搜索。
注意:第一个数与最后一个数和的判断。
代码如下:
#include<iostream>
#include<string.h>
using namespace std;
bool prime[40]; //素数标记数组
bool z[30]; //访问标记数组
int k[30],n; //k[i]记录素数环的具体情况
void dfs(int id,int b) //id表示素数环中的第几个数 b表示数是什么
{
z[b]=1;
k[id]=b;
if(id==n)
{
if(prime[b+k[1]])
{
cout<<"1";
for(int j=2;j<=n;j++)
cout<<" "<<k[j];
cout<<endl;
}
return;
}
for(int j=1;j<=n;j++)
{
if(z[j]==0&&prime[j+b])
{
dfs(id+1,j);
z[j]=0;
}
}
}
int main()
{
memset(prime,1,sizeof(prime));
for(int i=2; i<=39; i++) //筛法求素数
{
if(prime[i]==1)
{
for(int j=i+i; j<=39; j+=i)
prime[j]=0;
}
}
int flag=1;
while(cin>>n)
{
cout<<"Case "<<flag++<<":"<<endl;
memset(z,0,sizeof(z));
dfs(1,1);
cout<<endl;
}
return 0;
}
本文介绍了一种通过筛法求素数,然后使用深度优先搜索(DFS)算法解决寻找特定环形排列的问题,每个排列中相邻元素之和为素数。
147

被折叠的 条评论
为什么被折叠?



