hdu 1016 Problem Description (广搜)
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
还是一道广搜的题目,貌似还是花了很长的时间。
虽然说自己的做法可能有些啰嗦,没有大神们的代码精简。
不过还是贴出来,留着以后自己再慢慢优化吧。
View Code
1 #include<iostream> 2 #include<math.h> 3 using namespace std; 4 5 int num[30]; 6 int N , Count; 7 int vis[30]; 8 int sushu[100]; 9 int fun(int n) 10 { 11 int i , flag1 = 1 , flag2 = 1; 12 for(i = 2; i <=n; i++) 13 { 14 int temp = num[i] + num[i-1]; 15 if(!sushu[temp]) 16 flag1 = 0; 17 } 18 if(n == N) 19 { 20 int temp = num[N] + 1; 21 if(!sushu[temp]) 22 flag2 = 0; 23 } 24 if(flag1 && flag2) return 1; 25 else return 0; 26 } 27 28 int dfs(int *num , int n) 29 { 30 int i , j; 31 for(i = 2; i <= N; i++) 32 { 33 if(vis[i]) continue; 34 num[n] = i; 35 vis[i] = 1; 36 if(n>2 && !fun(n)) 37 { 38 vis[i] = 0; 39 continue; 40 } 41 if(n == N && fun(n)) 42 { 43 for(j = 1; j <= N; j++) 44 { 45 cout<<num[j]; 46 if(j != N) cout<<' '; 47 } 48 cout<<endl; 49 vis[i] = 0; 50 continue; 51 } 52 dfs(num , n+1); 53 vis[i] = 0; 54 } 55 return 0; 56 } 57 58 59 void find() //生成素数 60 { 61 int i; 62 sushu[1] = 1; 63 sushu[2] = 1; 64 for(i = 3; i <100; i++) 65 { 66 int temp , j , flag = 0; 67 temp = (int)sqrt(double(i)); 68 for(j = 2; j <= temp; j++) 69 { 70 if(i % j == 0) 71 flag = 1; 72 } 73 if(!flag) sushu[i] = 1; 74 } 75 } 76 int main() 77 { 78 num[1] = 1; 79 memset(sushu , 0 , sizeof(sushu)); 80 find(); 81 Count = 1; 82 while(cin>>N) 83 { 84 cout<<"Case "<<Count<<":"<<endl; 85 Count++; 86 memset(vis , 0,sizeof(vis)); 87 vis[1] = 1; 88 dfs(num , 2); 89 cout<<endl; 90 } 91 return 0; 92 }
既然选择了这条路,就应该坚持下去。

浙公网安备 33010602011771号