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的全排列中相邻两个和是素数包括第一个和最后一个的排列;
思路:
由于n最大20所以可以打一个素数表, if(num==n&&prime[a[n-1]+a[0]])搜索结束条件,其他的看注释;
代码:
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
using namespace std;
int prime[40]= {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};
int n;
int a[100],vis[100];
void dfs(int num)
{
if(num==n&&prime[a[n-1]+a[0]])
{
for(int i=0; i<n-1; i++)
{
printf("%d ",a[i]);
}
printf("%d\n",a[n-1]);
}
else
{
for(int i=2; i<=n; i++)
{
if(!vis[i]&&prime[i+a[num-1]])
{
vis[i]=1;//标记;
a[num]=i;//num此时等于1//由于第一个数是1,所以1已经被用过了,得从2开始往数组a里面存;
dfs(num+1);
vis[i]=0; //回溯;
}
}
}
}
int main()
{
int t=0;
while(~scanf("%d",&n))
{
t++;
printf("Case %d:\n",t);
memset(vis,0,sizeof(vis));
a[0]=1;
dfs(1);
printf("\n");
}
}