HDU 1016Prime Ring Problem

Posted 谦谦君子,陌上其华

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HDU 1016Prime Ring Problem相关的知识,希望对你有一定的参考价值。

http://acm.hdu.edu.cn/showproblem.php?pid=1016

题意:输入一个数,给出符合要求的素数环。

经典的dfs遍历。

 1 #include<iostream>
 2 #include<cstring>
 3 #include<cmath>
 4 using namespace std;
 5 
 6 int visited[25];
 7 int pos[25];
 8 int n, kase = 0;
 9 
10 int judge(int x)                 //判断是否为素数
11 {
12     for (int i = 2; i <= sqrt(x); i++)
13     {
14         if (x%i == 0)     return 0;
15     }
16     return 1;
17 }
18 
19 void dfs(int x,int count)
20 {
21     pos[count] = x;
22     visited[x] = 1;
23     if (count == n && judge(x + pos[1]))
24     {
25         for (int i = 1; i < n; i++)
26             cout << pos[i] << " ";
27         cout << pos[n];
28         cout << endl;
29     }
30     for (int k = 2; k <= n; k++)
31     {
32         if (!visited[k] && judge(k+pos[count]))
33         {
34             dfs(k, count+1);
35             visited[k] = 0;
36         }
37     }
38 }
39 
40 int main()
41 {
42     while (cin >> n && n)
43     {
44         memset(visited, 0, sizeof(visited));
45         memset(pos, 0, sizeof(pos));
46         kase++;
47         cout << "Case " << kase << ":" << endl;
48         dfs(1,1);
49         cout << endl;
50     }
51     return 0;
52 }

 

以上是关于HDU 1016Prime Ring Problem的主要内容,如果未能解决你的问题,请参考以下文章

hdu1016 Prime Ring Problem

HDU 1016 Prime Ring Problem(DFS)

HDU-1016-Prime Ring Problem

Prime Ring Problem HDU - 1016 (dfs)

Prime Ring Problem HDU - 1016

HDU 1016 Prime Ring Problem