Prime Ring Problem

                                                 Prime Ring Problem

                                              Time Limit: 2000ms                                         Memory Limit: 32768KB
                                                             64-bit integer IO format:      Java class name:
 
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 <iostream>
 2 #include<cstring>
 3 #include<cmath>
 4 using namespace std;
 5 int d[22];
 6 int a[22];
 7 int n,t=1;
 8 
 9 int zs(int x)  //判断是否为质数
10 {
11     for(int i=2;i<=(int)sqrt(x);i++)
12         if(x%i==0)
13            return 0;
14         return 1;
15 }
16 void dfs(int x,int cnt)
17 {
18     if(cnt==n)   //打表输出
19     {
20         for(int i=0;i<n-1;i++)
21             cout<<a[i]<<" ";
22         cout<<a[n-1]<<endl;
23     }
24     if(cnt>n)
25         return;
26     for(int i=2;i<=n;i++)
27         if(!d[i]&&zs(i+x))
28         {
29             if(cnt==n-1)
30                 if(!zs(i+a[0]))  //不要忘记判断最后一个数和第一个数
31                    continue;
32             a[cnt]=i;
33             d[i]=1;        //写入环中,标记为1
34             dfs(i,cnt+1);
35             d[i]=0;         //不符合要求,重新标记为0
36         }
37 }
38 int main()
39 {
40     while(cin>>n)
41     {
42         memset(d,0,sizeof(d));
43         a[0]=1;
44         d[1]=1;          //第一个必定为1,不要忘记标记
45         cout<<"Case "<<t++<<":"<<endl;
46         dfs(1,1);
47         cout<<endl;
48     }
49     return 0;
50 }
原文地址:https://www.cnblogs.com/q-c-y/p/5414535.html