http://vjudge.net/problem/UVA-524
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <set>
#include <iterator>
#include <iostream>
using namespace std;
int isp[50];
int n, a[20], vis[20];
int is_prime(int num)
{
for (int i = 2; i * i <=num; i++) {
if (num % i == 0) return 0;
}
return 1;
}
void dfs(int cur)
{
if (cur == n && isp[a[0] + a[n - 1]]) {
for (int i = 0; i < n - 1; i++) printf ("%d ", a[i]);
printf ("%d", a[n - 1]);
printf ("\n");
} else {
for (int i = 2; i <= n; i++) {
if (!vis[i] && isp[i + a[cur - 1]]) {//如果和旁边的数和不为素数,则直接回溯
a[cur] = i;
vis[i] = 1;
dfs (cur + 1);
vis[i] = 0;
}
}
}
}
int main()
{
#ifndef ONLINE_JUDGE
freopen ("in.txt", "r", stdin);
#endif // ONLINE_JUDGE
int kase = 1;
while (scanf ("%d", &n) != EOF) {
if (kase != 1) {printf ("\n");}
printf ("Case %d:\n", kase++);
for (int i = 2; i <= n * 2; i++) isp[i] = is_prime (i);
memset (a, 0, sizeof(a));
memset (vis, 0, sizeof(vis));
a[0] = 1;
vis[1] = 1;
dfs (1);
}
return 0;
}