题意:很容易理解,就是让你输出满足相邻的相加是素数的序列(注意不要重复)
思路就是深搜思想把每种情况遍历一次
代码实现:
#include<iostream>
#include<cstring>
using namespace std;
//素数打表标记每个素数,因为n最大是20,所以只要打到40
bool prime[40] = { 0,1,1,1,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,0,0,0,0,1,0,1,0,0,0,0,0,1,0,0 };
int f[21], n;
bool book[21];
void dfs(int num) {
if (n == num && prime[f[num - 1] + f[0]]) {
for (int i = 0; i < num - 1; ++i)
printf("%d ", f[i]);
cout << f[num - 1] << endl;
}
else {
for (int i = 2; i <= n; ++i) {
if (!book[i] && prime[i + f[num - 1]]) {
book[i] = true;
f[num++] = i;
dfs(num);
book[i] = 0;
--num;
}
}
}
}
int main() {
int num = 0;
while (scanf("%d", &n) != EOF)
{
num++;
printf("Case %d:
", num);
memset(book, 0, sizeof(book));
f[0] = 1;
dfs(1);
printf("
");
}
return 0;
}