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): 47403    Accepted Submission(s): 20954

 

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

 

题意:

给定一个数n,求1~n的n个自然数组成的环相邻两两相加为素数。

 

dfs可解,每搜到一个可行值就继续直到找出所有n个数,再回溯找另一种可能。

 

AC代码:

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 
 4 int a[21],n;
 5 bool vis[21];
 6 
 7 int prime(int a){//判断素数 
 8     if(a<2)
 9     return 0;
10     for(int i=2;i*i<=a;i++){
11         if(a%i==0)
12         return 0;
13     }
14     return 1;
15 }
16 
17 void dfs(int s){
18     if(s==n&&prime(a[1]+a[n])){//满足条件就输出 
19         for(int i=1;i<n;i++)
20         cout<<a[i]<<" ";
21         cout<<a[n]<<endl;
22     }
23     else{
24         for(int i=2;i<=n;i++){
25             if(vis[i]==0&&prime(a[s]+i)){
26                 vis[i]=1;//标为已用 
27                 a[s+1]=i;//加入环 
28                 dfs(s+1);
29                 vis[i]=0;//标记更新,回溯 
30             }
31         } 
32     }
33     
34 }
35 
36 int main(){
37     int ans=1;
38     while(cin>>n){
39         memset(a,0,sizeof(a));
40         memset(vis,0,sizeof(vis));
41         a[1]=1; 
42         cout<<"Case "<<ans++<<":"<<endl;
43         dfs(1);
44         cout<<endl;
45     }
46     return 0;
47 } 

 

posted @ 2017-02-28 21:12  Kiven#5197  阅读(290)  评论(0编辑  收藏  举报