标签:des style blog java color os
Prime Ring Problem Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 25134 Accepted Submission(s): 11222 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
题目意思就是给一个数n,1-n数字围成一个环,环中每两个相邻的数字相加为素数,把满足条件所有环输出,1始终为第一个数字。
感觉是深搜,于是水过了。。
代码:
1 #include <stdio.h> 2 #include <iostream> 3 #include <string.h> 4 #include <algorithm> 5 #include <math.h> 6 #include <vector> 7 using namespace std; 8 9 int used[20]; 10 int p[40]; 11 int n; 12 vector<int>a; 13 int kase; 14 void dfs(int k) 15 { 16 if(k>=n) 17 { 18 if(!p[a[0]+a[n-1]]) //数组首位相连构成环,首位相加为素数才满足条件 19 { 20 printf("%d",a[0]); 21 for(int i=1;i<a.size();i++) 22 printf(" %d",a[i]); 23 printf("\n"); 24 } 25 return; 26 } 27 for(int i=2;i<=n;i++) 28 { 29 int b=a[a.size()-1]; 30 if(!used[i]&&!p[b+i]) 31 { 32 a.push_back(i); 33 used[i]=1; 34 dfs(k+1); 35 a.pop_back(); 36 used[i]=0; 37 } 38 } 39 } 40 main() 41 { 42 int i, j, k; 43 memset(p,0,sizeof(p)); 44 p[1]=1;p[2]=0; 45 for(i=2;i<=40;i++) //筛选法求素数 46 { 47 for(j=2;j*i<=40;j++) 48 p[j*i]=1; 49 } 50 kase=1; 51 while(scanf("%d",&n)==1) 52 { 53 54 memset(used,0,sizeof(used)); 55 used[1]=1; 56 a.clear(); 57 a.push_back(1); 58 printf("Case %d:\n",kase++); 59 dfs(1); 60 cout<<endl; 61 } 62 }
HDU 1016 素数环(深搜),布布扣,bubuko.com
标签:des style blog java color os
原文地址:http://www.cnblogs.com/qq1012662902/p/3825853.html