素环问题
圆环由n个圆组成,如图所示。将自然数1、2,…,n分别放入每个圆,并且两个相邻圆中的数字总和应为质数。
注意:第一个圆的数目应始终为1。
输入值
n(0 <n <20)。
输出量
输出格式如下所示。每一行代表环中从顺时针和逆时针1开始的一系列圆圈编号。数字顺序必须满足上述要求。按字典顺序打印解决方案。
您将编写一个完成上述过程的程序。
在每种情况下都打印空白行。
样本输入
6
8
样本输出
情况1:
1 4 3 2 5 6
1 6 5 2 3 4
情况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 <cstring>
#include <math.h>
#include <algorithm>
using namespace std;
int n;
bool used[21];
int ans[21];
int prime[50];
void Prime(){
memset(prime, -1, sizeof(prime));
prime[0] = prime[1] = 0;
for(int i = 2; i < 50; i++){
if(prime[i] == -1){
prime[i] = 1;
for(int j = i + i; j < 50; j += i)
prime[j] = 0;
}
}
}
bool dfs(int cnt){
if(cnt == n && prime[ans[n - 1] + ans[0]] == 1){
for(int i = 0; i < n; i++){
if(i == n - 1)
cout << ans[i] << endl;
else
cout << ans[i] << ' ';
}
//返回true的话,只输出第一组数据,要么返回false,要么什么也不返回
return false;
}
for(int i = 2; i <= n; i++)
if(!used[i] && prime[i + ans[cnt - 1]] == 1){
used[i] = true;
ans[cnt] = i;
if(dfs(cnt + 1))
return true;
used[i] = false;
}
return false;
}
int main(){
cin.tie(0);
cout.tie(0);
int Case = 0;
Prime();
while(~scanf("%d", &n)){
Case++;
memset(used, 0, sizeof(used));
//Note: the number of first circle should always be 1.
ans[0] = 1;
used[1] = true;
dfs(1);
cout << endl;
}
}