hdu 1016 Prime Ring Problem

Prime Ring Problem

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


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
 
Source
 
 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cmath>
 4 #include<cstdlib>
 5 #include<cstring>
 6 using namespace std;
 7 int prime[40],vis[40];
 8 int a[40],n;
 9 
10 int dfs(int x)
11 {
12     if(x==n && !prime[a[n]+a[1]])
13     {
14         for(int i=1;i<=n;i++)
15         {
16             if(i==1)
17             printf("%d",a[i]);
18             else
19             printf(" %d",a[i]);
20         }
21         printf("\n");
22     }
23     else
24     {
25         for(int i=2;i<=n;i++)
26         {
27             if(!vis[i] && !prime[i+a[x]])
28             {
29                 vis[i]=1;
30                 a[x+1]=i;
31                 dfs(x+1);
32                 vis[i]=0;
33             }
34         }
35     }
36 }
37 
38 int main()
39 {
40     int k=0,j;
41     while(cin >> n)
42     {
43         memset(prime,0,sizeof(prime));
44         memset(vis,0,sizeof(vis));
45         k++;
46 
47         prime[1]=1;
48         for(int i=2;i<=n*2;i++)
49         {
50             if(!prime[i])
51             for(j=i+i;j<=n*2;j+=i)
52             {
53                 prime[j]=1;
54             }
55         }
56         printf("Case %d:\n",k);
57         a[1]=1;
58         dfs(1);
59         printf("\n");
60     }
61     return 0;
62 }
View Code

 

 
posted @ 2014-11-20 00:15  煎饼馃子  阅读(136)  评论(0编辑  收藏  举报