HDU 1016 Prime Ring Problem

题目:
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
题意描述:
输入n (0 < n < 20)
计算并输出从1到n可以组成多少个素数环
解题思路:
属于搜索题,进行DFS搜索的时候进行筛选即可。
代码实现:
 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<math.h>
 4 int r[30],book[30];
 5 void dfs(int step);
 6 int n;
 7 int isp(int n);
 8 int main()
 9 {
10     int c=1;
11     while(scanf("%d",&n) != EOF)
12     {
13         printf("Case %d:\n",c++);
14         memset(book,0,sizeof(book));
15         r[1]=1;
16         dfs(2);
17         printf("\n");
18     }
19     return 0;
20 } 
21 void dfs(int step)
22 {
23     int i;
24     if(step==n+1)
25     {
26         printf("%d",r[1]);
27         for(i=2;i<=n;i++)
28             printf(" %d",r[i]);
29         printf("\n");
30     }
31     for(i=2;i<=n;i++)
32     {
33         if(book[i]==0)
34         {
35             if(step != n)
36             {
37                 if(isp(r[step-1]+i))
38                 {
39                     r[step]=i;
40                     book[i]=1;
41                     dfs(step+1);
42                 
43                     book[i]=0;
44                 }
45                 else
46                 continue;
47             }
48             else 
49             {
50                 if(isp(i+r[n-1])&&isp(1+i))
51                 {
52                     r[step]=i;
53                     book[i]=1;
54                     dfs(step+1);
55                 
56                     book[i]=0;    
57                 }
58                 else
59                 continue;    
60             }
61         } 
62     }
63     return ;
64 }
65 int isp(int n)
66 {
67     int i,k,flag=0;;
68     k=(int)sqrt(n);
69     for(i=2;i<=k;i++)
70     {
71         if(n % i==0)
72         {
73             flag=1;
74             break;
75         }
76     }
77     if(flag||n==1)
78     return 0;
79     else
80     return 1;
81 }

易错分析:

1、注意素数环,末尾的数不光跟前一个有关还和第一个数有关

posted @ 2017-08-01 20:40  Reqaw  阅读(153)  评论(0编辑  收藏  举报