HDU 1016 - Prime Ring Problem

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

Prime Ring Problem

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 10426    Accepted Submission(s): 4690


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
 
很经典的dfs加回溯,在白书上看过,所以很快就ac了。 需要注意不要忘了判断最后一个数是否与第一个数的和为素数,因为是素数环~~~呵呵~~
代码如下:
 1 #include<iostream>
2 #include<math.h>
3 #include<cstring>
4 using namespace std;
5 int prime[40];
6 int d[40];
7 int vis[40];
8 int is_prime(int x)
9 {
10 if(x <= 1)
11 return 0;
12 for(int i = 2; i <= sqrt(x); i++)
13 if(x % i == 0)
14 return 0;
15 return 1;
16 }
17 void dfs(int cur, int n)
18 {
19 if(cur == n)
20 {
21 if(prime[d[0] + d[n-1]])
22 {
23 for(int i = 0; i < n; i++)
24 {
25 printf("%d", d[i]);
26 if(i != n-1)
27 putchar(' ');
28 }
29 putchar(10);
30 }
31 return;
32 }
33 for(int i = 2; i <= n; i++)
34 {
35 if(!vis[i] && prime[i + d[cur-1]])
36 {
37 d[cur] = i;
38 vis[i] = 1;
39 dfs(cur + 1, n);
40 vis[i] = 0;
41 }
42 }
43 }
44 int main()
45 {
46 int n, cnum = 0;
47 for(int i = 0; i < 40; i++)
48 prime[i] = is_prime(i);
49 while(scanf("%d", &n) != EOF)
50 {
51 cnum++;
52 memset(vis, 0, sizeof(vis));
53 printf("Case %d:\n", cnum);
54 d[0] = 1;
55 dfs(1, n);
56 putchar(10);
57 }
58 return 0;
59 }
posted @ 2011-12-22 17:27  枫萧萧  阅读(206)  评论(0编辑  收藏  举报