hdu1016 Prime Ring Problem(回溯)
Prime Ring Problem
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 12105 Accepted Submission(s): 5497
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.

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.
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
题意:输入一个 n 找出1~n的组合,使得相邻两个数之和为素数;
分析:预处理40之间的素数,然后回溯;
View Code
1 #include<iostream> 2 #define N 25 3 #define M 40 4 using namespace std; 5 6 bool is_prime[M],visited[N]; 7 int n,test,ans[N]; 8 9 void work(int k) 10 { 11 int i; 12 if(k==n+1) 13 { 14 if(!is_prime[ans[n]+ans[1]]) return ; 15 for(i=1;i<=n-1;i++) 16 cout<<ans[i]<<" "; 17 cout<<ans[i]<<endl; 18 return ; 19 } 20 for(i=2;i<=n;i++) 21 { 22 if(!visited[i]&&is_prime[ans[k-1]+i]) 23 { 24 visited[i]=true; 25 ans[k]=i; 26 work(k+1); 27 visited[i]=false; 28 } 29 } 30 } 31 32 bool prime(int n) 33 { 34 if(n==1) return false; 35 if(n==2||n==3) return true; 36 int i; 37 for(i=2;i<n;i++) 38 if(n%i==0) 39 return false; 40 return true; 41 } 42 43 int main() 44 { 45 int i;test=1; 46 for(i=1;i<M;i++) is_prime[i]=prime(i); 47 while(cin>>n) 48 { 49 ans[1]=1; 50 memset(visited,false,sizeof(visited)); 51 cout<<"Case "<<test<<":"<<endl; 52 work(2); 53 test++; 54 cout<<endl; 55 } 56 return 0; 57 }


浙公网安备 33010602011771号