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
// 题目就是 最简单的深搜
// 另外,再 需要 写个 判断素数的函数
//找准,结束条件和回溯边界 ,这个题 就很容易解了
// 还是需要多练
#include<iostream>
using namespace std;
bool prime[41];
int num[21],n,vis[21];
bool isprime(int j){
if( j ==1)
return false;
for(int i=2;i*i<=j;i++)
if( j % i == 0 )
return false;
return true;
}
void print(){
for( int i =0;i<n;i++)
if(i<n-1)
printf("%d ",num[i]);
else printf("%d\n",num[i]);
}
void dfs(int cnt ){
if( cnt == n && prime[ num[0] + num[ n -1] ] ) // 结束地方
print();
else for(int i=2;i<=n;i++)
if( !vis[i] && prime[ num[cnt -1] + i ] ){
vis[i] = 1;
num[cnt] = i;
dfs(cnt+1);
vis[i] = 0; //回溯地方
}
}
int main(void){
for(int i=1;i<=40;i++)
prime[i] = isprime(i);
for(int i=1;i<=20;i++)
vis[i] = 0;
for(int i=1;i<=20;i++)
num[i] = 0;
int cnt =0 ;
while(scanf("%d",&n)!=EOF){
printf("Case %d:\n",++cnt);
num[0] = 1;
dfs(1);
printf("\n");// 题目有个小要求 ,每个 案例后 打印一个空格
}
return 0;
}