HDU 1016 Prime Ring Problem(DFS)

                          Prime Ring Problem

            Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)

                    Total Submission(s): 18636    Accepted Submission(s): 8350

Problem Description
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.
 
Input
n (0 < n < 20).
 
Output
The 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 <stdio.h>
 2 #include <string.h>
 3 #include <math.h>
 4 
 5 int N;
 6 const int MAX_N = 25;
 7 int arr[MAX_N];        //保存满足条件时各个数值
 8 int visit[MAX_N];      //记录某个数是否访问过
 9 int prime[MAX_N * 2];  //素数表
10 
11 void IsPrime()         //判断是否是素数
12 {
13     int i, k ;
14     memset(prime, 0, sizeof(prime));
15     for(int num = 2; num <= 45; num++)
16     {
17         k = sqrt((double)num);
18         for(i = 2; i <= k; i++)
19         {
20             if(num % i == 0)
21                 break;
22         }
23         if(i > k)
24             prime[num] = 1;
25     }
26 }
27 
28 void PrintResult()      //打印结果
29 {
30     printf("1");
31     for(int i = 2; i <= N; i++)
32         printf(" %d", arr[i]);
33     printf("\n");
34 }
35 
36 void dfs(int curValue, int curCount) //curValue代表当前值,curCount代表当前数组下标
37 {
38     if(curCount > N)return ;
39     if(curCount == N && prime[curValue + 1]) //满足条件,输出答案
40     {
41         PrintResult();
42         return ;
43     }
44 
45     for(int i = 2; i <= N; i++)
46     {
47         if(visit[i] == 0 && prime[i + curValue])
48         {
49             visit[i] = 1;             //标记为已访问
50             arr[curCount + 1] = i;
51             dfs(i, curCount + 1);     //搜索下一个
52             visit[i] = 0;             //回溯时恢复原来状态
53         }
54     }
55 }
56 
57 int main()
58 {
59     IsPrime();
60     int nCase = 0;
61     while(scanf("%d", &N) != EOF)
62     {
63         nCase++;
64         memset(visit, 0, sizeof(visit));
65         arr[1] = 1;
66         visit[1] = 1;
67 
68         printf("Case %d:\n", nCase);
69         dfs(1, 1);
70         printf("\n");
71     }
72     return 0;
73 }

 

 

posted @ 2013-05-26 18:56  Dreamcaihao  阅读(144)  评论(0编辑  收藏  举报