-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprime_ring_problem_uva524.cpp
67 lines (67 loc) · 1.25 KB
/
prime_ring_problem_uva524.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <iostream>
#include <cstring>
using namespace std;
const int maxn = 50;
int ans[maxn]; // 结果数组
int vis[maxn]; // 访问标记数组
int isp[maxn]; // 素数数组,方便计算
int n;
int is_prime(int x)
{
// 注意是i * i <= x,从2开始
for (int i = 2; i * i <= x; i++)
{
if (x % i == 0)
{
return 0;
}
}
return 1;
}
void display()
{
for (int i = 0; i < n; i++)
{
if (i != 0)
{
cout << ' ';
}
cout << ans[i];
}
cout << endl;
}
void dfs(int cur)
{
// 递归边界
// 判断头尾相加是否为素数
if (cur == n && isp[ans[0] + ans[n - 1]])
{
display();
return;
}
// 注意循环上下限
for (int i = 2; i <= n; i++)
{
// 如果i没有用过,并且与前一个数之和为素数
if (!vis[i] && isp[i + ans[cur - 1]])
{
ans[cur] = i;
vis[i] = 1;
dfs(cur + 1);
vis[i] = 0; // 撤销的是标记操作
}
}
}
int main()
{
cin >> n;
memset(vis, 0, sizeof(vis));
for (int i = 2; i <= n*2; i++)
{
isp[i] = is_prime(i);
}
ans[0] = 1;
dfs(1);
system("pause");
return 0;
}