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.
Note: the number of first circle should always be 1.
Inputn (0 < n < 20).
OutputThe 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,1—n组成一个环,相邻的两个整数为素数。输出时从整数1开始,逆时针排列。同一个环恰好输出一次,n (0 < n <20)
代码如下:
#include<iostream> using namespace std; int n; int a[20],book[20]; //素数模板 int sushu(int n) { if(n<2) return false; for (int i=2;i*i<=n; i++) { if(n%i==0) return false; } return true; } void dfs(int step) { //边界的处理 if(step==n&&sushu(a[1]+a[n])) //递归边界。别忘了测试第一个数和最后一个数 { { for(int i=1; i<n; i++) cout<<a[i]<<" "; cout<<a[n]<<endl;//空格的处理 } return ;//返回之前的一步(最近调用的地方) } for(int i=2; i<=n; i++) { if(book[i]==0&&sushu(i+a[step])) //如果i没有用过,并且与前一个数之和为素数 { //因为第一个已经存入,所以在这里a[step+1] a[step+1]=i; //放入(该位置存入值) book[i]=1; //将值设为1,表示已不在手上 dfs(step+1); //递归调用 book[i]=0; //清除标记 } } return; } int main() { int t=0; while(cin>>n) { a[1]=1; t++; cout<<"Case "<<t<<":"<<endl; dfs(1); cout<<endl; } return 0; }