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>
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>
6<br>8<br>
Case 1:<br>1 4 3 2 5 6<br>1 6 5 2 3 4<br><br>Case 2:<br>1 2 3 8 5 6 7 4<br>1 2 5 8 3 4 7 6<br>1 4 7 6 5 8 3 2<br>1 6 7 4 3 8 5 2<br>
题意:给出一个正整数,第一个数一定是一,然后搜索怎么排列能做成素数的环。
思路:就是广度搜索,符合要求就输出这一序列。
#include<iostream>
#include<cstring>
using namespace std;
int n,cnt = 1;
int vis[21],A[21];//存放进这之中
int primelist[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};//因为0<n<20所以这一范围内,素数就那么几个,这样搜索比较快
void dfs(int cur)//深度搜索
{
if(cur == n && primelist[A[0]+A[n-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] && primelist[i+A[cur-1]])
{
A[cur] = i;
vis[i] = 1;
dfs(cur + 1);
vis[i] = 0;
}
}
int main()
{
A[0] = 1;
while(cin >> n)
{
memset(vis,0,sizeof(vis));
cout << "Case " << cnt++ <<":\n";
dfs(1);
cout << endl;
}
return 0;
}