题目
题目出处:http://acm.hdu.edu.cn/showproblem.php?pid=1016
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.
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 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个数组成一个环,n个数为1,2,…,n自然数, 两两相邻相加和为素数,头尾相加也为素数,列出n个数时所有的排列情况。
思路
- 由于n非常小,所以可以先使用素数筛去寻找范围内的所有素数 。
- 再利用深搜对每种情况进行遍历,如果发现某个数的情况无法凑出一个环,进行回溯。直到所以遍历所有情况。
代码实现
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
using namespace std;
int n;
int vis[41];
int ans_num[21];
int prime_num[41];
void prime() //素数筛 找出40以内的素数.
{
memset(prime_num,0,sizeof(prime_num));
int m=sqrt(40);
prime_num[1]=1;
for(int i=2;i<=m;++i)
{
if(!prime_num[i])
{
for(int j=i*i;j<=40;j+=i)
{
prime_num[j]=1;
}
}
}
}
void dfs(int x) //深搜
{
if(x==n&&prime_num[ans_num[0]+ans_num[n-1]]==0) //当到该情况遍历到最后一个数时,比较头尾相加是否是素数是则符合进行输出
{
for(int i=0;i<n;++i)
{
if(i!=0) cout<<" ";
cout<<ans_num[i];
}
cout<<endl;
}
else //对每一个数进行适配搜索
{
ans_num[0]=1;
vis[1]=1;
for(int i=2;i<=n;++i) //对每种数字情况进行遍历
{
if(!vis[i]&&prime_num[i+ans_num[x-1]]==0) //如果该数没被使用过以及与上一个数相加为素数则符合条件
{
ans_num[x]=i; //把符合条件的数加入数组
vis[i]=1; //标记为已使用该数字
dfs(x+1); //对下一个数进行搜索
vis[i]=0; //回溯的关键,若数组x位置加x+1位置的数无论如何都不符合,则会回到这里对x位置的数进行变更,刷新数字的使用状态。
}
}
}
}
int main()
{
int m=1;
memset(vis,0,sizeof(vis));
prime();
while(cin>>n)
{
if(n==-1) break;
cout<<"Case "<<m++<<":"<<endl;
dfs(1);
cout<<endl;
}
}