Prime Ring Problem
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
图片就不放了。。做下笔记以后回来复习。。
code:
#include <iostream>
#include <cmath>
#include <cstring>
using namespace std;
int n,a[25],book[25];
int prime(int x)
{
int i;
for(i=2;i<=sqrt(x);i++)
if(x%i==0) break;
if(i<=sqrt(x)) return 0;
else return 1;
}
void dfs(int step)
{
int first=1;
a[n+1]=a[1];
a[1]=1;
book[1]=1;
if(step==n+1) {
if(prime(a[n]+a[1])==0) return ;//判断最后一个数和第一个数的和是不是素数
for (int i=1;i<=n;i++){
if(first) first=0;
else cout<<' ';
cout<<a[i];
}
cout<<endl;
} //用递归实现dfs,满足条件输出,不满足条件直接返回
for(int i=2;i<=n;i++){
if(book[i]==0 && prime(i+a[step-1])){ //在循环的时候判断,避免超时,减少运算次数。。
a[step]=i; //第一个位置放的数为i
book[i]=1; //表示已经用过i这个数
dfs(step+1);//递归调用
book[i]=0; //用完后还原,下次搜索时仍能访问
}
}
return ;
}
int main()
{
int sum=1;
memset(a,0,sizeof(a));
while(cin>>n){
cout<<"Case "<<sum<<':'<<endl;
sum++;
if(n%2==1) cout<<endl; //剪枝,不然会超时,数据太大
else {
memset(book,0,sizeof(book));
dfs(2);
cout<<endl;
}
}
return 0;
}