#Description
Input n
由1…n组成一个环
任意两个相邻的环的和是 质数
输出所有可能的解
#Algorithm
递归搜索就可以
#Hint
行末不能有空行,否则会PE
#Code
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
int n;
const int maxn = 16 + 9;
int a[maxn];
bool b[maxn];
void print()
{
printf("%d", a[0]);
for (int i = 1; i < n; i++)
printf(" %d", a[i]);
putchar('\n');
}
bool isPrime(const int &x)
{
bool flag = true;
for (int i = 2; i * i <= x; i++)
if (x % i == 0)
{
flag = false;
break;
}
return flag;
}
void dfs(const int &x)
{
if (x == n)
{
if (isPrime(a[0] + a[x - 1]))
{
print();
}
return;
}
for (int i = 2; i <= n; i++)
if (!b[i] && isPrime(a[x - 1] + i))
{
a[x] = i;
b[i] = true;
dfs(x + 1);
b[i] = false;
}
}
void solve()
{
memset(a, 0, sizeof(a));
a[0] = 1;
memset(b, 0, sizeof(b));
b[1] = true;
dfs(1);
}
int main()
{
int i = 0;
scanf("%d", &n);
printf("Case %d:\n", ++i);
solve();
while (scanf("%d", &n) != EOF)
{
printf("\nCase %d:\n", ++i);
solve();
}
}