素環問題
圓環由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;
}
}