题意:素数环。
方法:回溯,参见刘汝佳《算法入门经典》P127。
注意:有些n没有素数环,例如11。。刚开始以为程序除了问题,用了uva toolkit才知道的,数和数之间的空格,样例之间空行卡的很严,注意!
#include <iostream>
#include <iomanip>
#include <string>
#include <cstring>
#include <cstdio>
#include <queue>
#include <stack>
#include <algorithm>
#include <cmath>
using namespace std;
int isp[100], A[20], vis[20], n = 0;
int is_prime(int n)
{
int i = 0;
for (i = 2; i <= sqrt(n); i++)
if (0 == n % i)
return 0;
return 1;
}
void dfs(int cur)
{
int i = 0, j = 0;
if (cur == n && isp[A[0] + A[cur-1]])
{
for (i = 0; i < n; i++)
{
if (i != n-1)
cout << A[i] << " ";
else
cout << A[i];
}
cout << endl;
}
else
{
for (i = 2; i <= n; i++)
{
if (!vis[i] && isp[i+A[cur-1]])
{
vis[i] = 1;
A[cur] = i;
dfs(cur+1);
vis[i] = 0;
}
}
}
}
int main()
{
#ifdef Local
freopen("a.in", "r", stdin);
freopen("a.out", "w", stdout);
#endif
int i = 0, t = 0;
while(cin >> n)
{
memset(A, 0, sizeof(A));
memset(vis, 0, sizeof(vis));
memset(isp, 0, sizeof(isp));
if (t)
cout << endl;
cout << "Case " << ++t << ":" << endl;
for (i = 2; i <= n*2; i++)
isp[i] = is_prime(i);
A[0] = 1;
dfs(1);
}
}