Prime Ring Problem
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 66883 Accepted Submission(s): 28675
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
clockwisely 顺时针地
anticlockwisely 逆时针地
lexicographical 字典序地
比较典型的dfs。注意格式要求,每一组的最后一个数据后面没有空格。
AC代码:
1 #include<iostream> 2 #include<sstream> 3 #include<algorithm> 4 #include<string> 5 #include<cstring> 6 #include<iomanip> 7 #include<vector> 8 #include<cmath> 9 #include<ctime> 10 #include<stack> 11 using namespace std; 12 int N,a[21],book[21]; 13 bool isprime(int n)//n是否为素数 14 { 15 if(n==2||n==3) return 1; 16 if(n%6!=1&&n%6!=5) return 0; 17 int b=sqrt(n); 18 for(int i=5;i<=b;i+=6) 19 if(n%i==0||n%(i+2)==0) return 0; 20 return 1; 21 } 22 void dfs(int step) 23 { 24 if(step==N+1) 25 { 26 if(isprime(a[1]+a[N])) 27 { 28 for(int j=1;j<=N;j++) 29 if(j!=N) cout<<a[j]<<' '; 30 else cout<<a[j]; 31 cout<<endl; 32 } 33 return; 34 } 35 for(int i=2;i<=N;i++) 36 { 37 if(book[i]) continue; 38 if(isprime(i+a[step-1])) 39 { 40 book[i]=true; 41 a[step]=i; 42 dfs(step+1); 43 book[i]=false;//回溯 44 } 45 } 46 } 47 int main() 48 { 49 int count=1; 50 while(cin>>N) 51 { 52 memset(book,0,sizeof(0)); 53 a[1]=1; 54 cout<<"Case "<<count++<<": "; 55 dfs(2); 56 cout<<endl; 57 } 58 } 59