HDU 1016 Prime Ring Problem(dfs)

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<cstdio>
 2 #include<string.h>
 3 #include<cmath>
 4 #include<algorithm>
 5 using namespace std;
 6 int n,cnt;
 7 int prime(int x){//判断素数 
 8     if(n==1)
 9         return 0;
10     if(n==2)
11         return 1;
12     for(int i=2;i<=floor(sqrt(x));i++){
13         if(x%i==0)
14             return 0;
15     }
16     return 1;
17 }
18 
19 int vis[30],a[30];
20 void dfs(int x){
21     if(x==n&&prime(a[n]+1)){//如果正好轮了n个数,且相邻之和都为素数,输出 
22         for(int i=1;i<=n-1;i++){
23             printf("%d ",a[i]);
24         }    
25         printf("%d\n",a[n]);    
26     }
27     for(int i=2;i<=n;i++){ //从2-n一个一个试下去 
28         a[cnt]=i;
29         if(prime(a[cnt]+a[cnt-1])&&vis[i]==0){ //然后是素数且没有用过就继续 
30             vis[i]=1;//标记用过 
31             cnt++;
32             dfs(x+1);
33             vis[i]=0;//回溯 
34             cnt--;
35         }
36     }
37 }
38 
39 int main(){
40     int q=1;
41     while(scanf("%d",&n)!=EOF){
42         printf("Case %d:\n",q++);
43         memset(vis,0,sizeof(vis));
44         memset(a,0,sizeof(0));
45         vis[1]=1;
46         a[1]=1;
47         cnt=2;
48         dfs(1);        
49         printf("\n");
50     }
51     return 0; 
52 }

 

posted on 2018-12-29 19:29  甜甜圈不懂巧克力的苦  阅读(103)  评论(0编辑  收藏  举报

导航