HDU 1016 素数环(DFS)

              Prime Ring Problem



 

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
 
如果是奇数直接No Answer,搜索的时候加上判断当前项和前一项和是否是素数的剪枝。
 
 1 #include<cstdio>
 2 #include<cstring>
 3 using namespace std;
 4 
 5 int n,a[21],p[41]={0};
 6 bool used[21];
 7 bool flag,key;
 8 
 9 void init()
10 {
11     for(int i=2;i*i<40;i++)
12     for(int j=i+i;j<40;j+=i)
13     p[j]=1;
14 }
15 
16 bool check(void)
17 {
18     for(int i=0;i<n;i++)
19     if(p[a[i]+a[(i+1)%n]])
20     return false;
21     return true;
22 }
23 
24 void dfs(int cur)
25 {
26     int i;
27     if(cur==n)
28     {
29         if(check())
30         {
31             flag=true;
32             for(i=0;i<n-1;i++)
33             printf("%d ",a[i]);
34             printf("%d
",a[i]);
35         }
36         return;
37     }
38     for(i=2;i<=n;i++)
39     {
40         if(!used[i]&&!p[i+a[cur-1]])
41         {
42             a[cur]=i;
43             used[i]=true;
44             dfs(cur+1);
45             used[i]=false;
46         }
47     }
48 }
49 
50 int main()
51 {
52     int i,j;
53     init();
54     int kase=0;
55     while(scanf("%d",&n)!=EOF)
56     {
57         a[0]=1,flag=false,used[1]=true;
58         memset(used,0,sizeof(used));
59         if(n%2&&n!=1)
60         {
61             printf("No Answer

");
62             continue;
63         }
64         printf("Case %d:
",++kase);
65         dfs(1);
66         if(!flag)
67         printf("No Answer
");
68         printf("
");
69     }
70     return 0;
71 }
原文地址:https://www.cnblogs.com/homura/p/4693018.html