颜良某天ak太多了心烦,想带领小伙伴们做游戏 。
游戏内容如下:
当颜良喊出一个数字n时,便有n个小伙伴,身上带着1到n的数字,手牵手拉成一个环。当环里的每个人相邻两人身上数字之和都为素数时,便找到了一个环。当找出所有的环时,游戏便结束。
Note: 每个环的第一个数字必须是1
Input
n (0 < n < 20).
Output
输出格式如下方输出样例所示。
每行一串数字表示一种环中数字的排列顺序。数字的顺序必须满足:从1开始,顺时针或逆时针。按字典序输出所有解决方案。您将编写一个完成上述过程,帮助大家顺利完成游戏的程序。别忘了在每组方案后面输出一个空行。
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
分析:使用深搜DFS来解决问题,要注意每个环的第一个数字必须是1,而且要注意1与最后一个数字之和也要是素数,这一点不要忽略。
代码如下:
#include"iostream"
#include"stdio.h"
#include"cstring"
#include"vector""
#include"queue"
#include"algorithm"
using namespace std;
int a[100],b[100];
int n,cnt=0;
int isprime(int x)
{
int i;
for(i=2;i*i<=x;i++)
{
if(x%i==0)
return 0;
}
return 1;
}
void dfs(int x,int y)
{
for(int i=1;i<=n;i++)
{
if(b[i]==0)
{
if(isprime(x+i)==1)
{
b[i]=1;
a[y]=i;
dfs(i,y+1);
b[i]=0;
}
}
}
if(y==n+1)
{
if(isprime(x+1)==1)
{
for(int i=1;i<n;i++)
printf("%d ",a[i]);
printf("%d\n",a[n]);
}
}
}
int main()
{
while(cin>>n)
{
printf("Case %d:\n",++cnt);
a[1]=1;
b[1]=1;
dfs(1,2);
printf("\n");
}
return 0;
}