A ring is composed of n (even number) circles as shown in diagram. Put natural numbers 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 ≤16)
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.
You are to write a program that completes above process.
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
HINT
回溯法解决,直接无脑暴力破解工作量巨大。结合使用深度优先遍历递归,每次递归完成之后将其恢复原状,大大节省时间。另外,由于n<=16,最大的和素数为31,直接枚举出来即可。
Accepted
#include<iostream>
#include<algorithm>
#include<cstring>
#include<set>
#include<vector>
using namespace std;
int n, Case = 0;
vector<int>list; int vis[17] = { 0 };
set<int>prime_number = { 2,3,5,7,11,13,17,19,23,29,31 };
void dfs(int num) {
if (num == n && prime_number.count(list.front() + list.back()))
for (int i = 0; i < n; i++)cout << list[i] << (i == n - 1 ? '\n' : ' ');
else for(int i=2;i<=n;i++)
if (!vis[i] && prime_number.count(i + list.back())) {
list.push_back(i); vis[i] = 1;
dfs(num + 1);
list.pop_back(); vis[i] = 0;
}
}
int main() {
while (cin >> n) {
cout << (Case == 0 ? "" : "\n");
memset(vis, 0, sizeof(vis));
list.clear();
cout <<"Case " << ++Case <<':'<< endl;
list.push_back(1); vis[1] = 1;
dfs(1);
}
}