【题意】把1-n,连续的放到一个环里,使相邻的数字和为素数,输出所有结果。

【解题方法】回溯法的简单应用。

【AC代码】

//
//Created by just_sort 2016/1/5
//Copyright (c) 2016 just_sort.All Rights Reserved
//

//#include <ext/pb_ds/assoc_container.hpp>
//#include <ext/pb_ds/tree_policy.hpp>
//#include <ext/pb_ds/hash_policy.hpp>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <cmath>
#include <cstdio>
#include <time.h>
#include <cstdlib>
#include <cstring>
#include <sstream> //isstringstream
#include <iostream>
#include <algorithm>
using namespace std;
//using namespace __gnu_pbds;
typedef long long LL;
typedef pair<int, LL> pp;
#define REP1(i, a, b) for(int i = a; i < b; i++)
#define REP2(i, a, b) for(int i = a; i <= b; i++)
#define REP3(i, a, b) for(int i = a; i >= b; i--)
#define CLR(a, b) memset(a, b, sizeof(a))
#define MP(x, y) make_pair(x,y)
const int maxn = 1e3 + 10;
const int maxm = 2e5;
const int maxs = 10;
const int maxp = 1e3 + 10;
//const int INF = 1e9;
const int UNF = -1e9;
const int mod = 1e9 + 7;
int gcd(int x, int y) {return y == 0 ? x : gcd(y, x % y);}
//typedef tree<int,null_type,less<int>,rb_tree_tag,tree_order_statistics_node_update>order_set;
//head
bool vis[50];
void init(){
for(int i = 2; i < 50; i++){
if(vis[i]) continue;
for(int j = 2 * i; j < 50; j += i) vis[j] = true;
}
}
int n, A[20];
bool vis2[20];
void dfs(int cur)
{
if(cur == n && !vis[A[0] + A[n - 1]]){
REP1(i, 0, n - 1) printf("%d ", A[i]); printf("%d\n", A[n - 1]);
}
else REP2(i, 2, n){
if(!vis2[i] && !vis[i + A[cur - 1]]){
A[cur] = i;
vis2[i] = 1;
dfs(cur + 1);
vis2[i] = 0;
}
}
}
int main()
{
init();
int ks = 0;
while(scanf("%d", &n) != EOF)
{
CLR(vis2, 0);
A[0] = 1;
if(ks++) puts("");
printf("Case %d:\n", ks);
dfs(1);
}
return 0;
}