基础dfs加了点回溯的思想,WA了一发原因是输出结果没加冒号,ORZ。
#include <bits/stdc++.h>
using namespace std;
int num[25];
bool vis[25];
bool prime[50];
int n;
void get_prime()
{
memset(prime, true, sizeof(prime));
prime[0] = false;
prime[1] = false;
for (int i = 2; i < 50; i++) {
for (int j = 2; i*j < 50; j++) {
prime[i*j] = false;
}
}
}
void dfs(int inx, int times)
{
num[times] = inx;
if (times == n-1) {
int sum = num[times] + num[0];
if (prime[sum]) {
for (int i = 0; i < n; i++) {
if (i) cout << " " ;
cout << num[i] ;
}
cout << endl;
}
return ;
}
for (int i = 2; i <= n; i++) {
if (!vis[i] && prime[i+inx]) {
vis[i] = true;
dfs(i, times+1);
vis[i] = false;
}
}
}
void Memset()
{
memset(vis, false, sizeof(vis));
vis[1] = true;
}
int main()
{
ios::sync_with_stdio(false);
int cas = 1;
num[0] = 1;
get_prime();
while (cin >> n)
{
Memset();
cout << "Case " << cas++ << ":" << endl;
for (int i = 2; i <= n; i++) {
if (prime[1+i]) {
vis[i] = true;
dfs(i, 1);
vis[i] = false;
}
}
cout << endl;
}
return 0;
}