Prime Ring Problem HDU - 1016 (dfs)

Posted fengzeng666

tags:

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

Prime Ring Problem

 HDU - 1016 

 

A ring is compose of n circles as shown in diagram. Put natural number 1, 2, ..., n into each circle separately, and the sum of numbers in two adjacent circles should be a prime. 

Note: the number of first circle should always be 1. 

技术图片 

Inputn (0 < n < 20). 
OutputThe output format is shown as sample below. Each row represents a series of circle numbers in the ring beginning from 1 clockwisely and anticlockwisely. The order of numbers must satisfy the above requirements. Print solutions in lexicographical order.

You are to write a program that completes above process. 

Print a blank line after each case. 
Sample Input

6
8

Sample Output

Case 1:
1 4 3 2 5 6
1 6 5 2 3 4

Case 2:
1 2 3 8 5 6 7 4
1 2 5 8 3 4 7 6
1 4 7 6 5 8 3 2
1 6 7 4 3 8 5 2

 1 #include<iostream>
 2 #include<stdio.h>
 3 #include<cstring>
 4 #include<queue>
 5 
 6 using namespace std;
 7 
 8 
 9 int n;
10 int a[23];
11 int vis[23];
12 bool mark[1000];
13 
14 void init()        // 素数筛 
15 
16     for(int i = 2; i < 1000; ++i)
17         mark[i] = true;
18     
19     for(int i = 2; i < 1000; ++i)
20     
21         if(mark[i] == true)
22         
23             for(int j = i*i; j < 1000; j += i)
24             
25                 mark[j] = false;
26             
27         
28     
29 
30 
31 // 边枚举边判断,不要最后一次性判断,会超时 
32 void dfs(int step)
33 
34     if(step > 2)
35     
36         if(mark[a[step-1]+a[step-2]] == false)    // 判断最后两个数 
37             return;
38     
39     
40     if(step == n+1)
41     
42         if(mark[a[n]+a[1]] == false)    // 判断最后一个数与第一个数 
43             return;
44         for(int i = 1; i < n; ++i)
45             printf("%d ", a[i]);
46         printf("%d\n", a[n]);
47 
48     
49             
50     for(int i = 2; i <= n; ++i)
51     
52         if(!vis[i])
53         
54             a[step] = i;
55             vis[i] = 1;
56             dfs(step+1);
57             vis[i] = 0;
58         
59         
60     
61 
62 
63 
64 int main()
65 
66      init();
67      int cas = 1;
68      a[1] = 1;
69      while(scanf("%d", &n) != EOF)
70      
71          printf("Case %d:\n", cas++);
72          memset(vis, 0, sizeof(vis));
73          dfs(2);
74          printf("\n");
75      
76     
77     
78     return 0;
79 

 

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

hdu1016 Prime Ring Problem

HDU 1016 Prime Ring Problem

HDU-1016-Prime Ring Problem

Prime Ring Problem HDU - 1016

HDU 1016 Prime Ring Problem

HDU 1010 Prime Ring Problem