经典深搜,注意那个顺时针与逆时针序,其实只用考虑顺时针就好,也就是说只要考虑与前一个数相加是否为素数即可。题不难,主要是对dfs递归理解要到位O(∩_∩)O~~
#include<iostream>
#include<cstring>
using namespace std;
int n;
int num[21],mark[21];
int prime[12] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37 };
int isPrime(int b)
{
for (int i=0; i<12; i++)
{
if (b == prime[i])
{
return 1;
}
}
return 0;
}
void dfs(int step)
{
if (step-1==n && isPrime(num[step-1]+1))
{
for (int i=1; i<n; i++)
{
printf("%d ",num[i]);
}
printf("%d\n",num[n]);
return;
}
for (int i=2; i<=n; i++)
{
if (mark[i] && isPrime(num[step-1]+i)) //标记为1是没用过,为0是用过
{
num[step] = i;
mark[i] = 0;
dfs(step+1);
mark[i] = 1;
}
}
}
int main()
{
int cont = 1;
while (scanf("%d",&n) != EOF)
{
memset(mark,0,sizeof(mark));
memset(num,0,sizeof(num));
printf("Case %d:\n",cont++);
for (int i=1; i<=n; i++)
{
mark[i] = 1;
}
num[1] = 1;
if (n==1)
{
printf("1\n\n");
continue;
}
dfs(2);
printf("\n");
}
}