prime ring problem|素数环问题
题目分析
相邻的数字相加为素数,dfs搜索,最后看头和尾相加是否为素数;
注意这题特别容易PE。。。
每一行最后不能加空格
每一个case之间要空行且第一个case不能空行
代码
#include<iostream>
#include<string.h>
using namespace std;
int book[20],a[20];
int n,z=1;
int zhishu(int k)
{
for (int i = 2; i < k; i++)if (k % i == 0)return 0;return 1;
}
void dfs(int s)
{
if (s == n && zhishu(a[n] + 1)){
for (int j = 1; j < n; j++)cout << a[j]<<" ";cout << a[n] << endl;}else{
for (int p = 2; p <= n; p++)if (zhishu(a[s] + p) && book[p] != 1){
a[s + 1] = p;book[p] = 1;dfs(s + 1);book[p] = 0;}}
}
int main()
{
while (cin >> n){
if (z >= 2)cout << endl;memset(a, 0, sizeof(a));memset(book, 0, sizeof(book));a[1] = 1;cout << "Case " << z <<":" << endl;dfs(1);z++;}return 0;
}