刷回溯的时候发现我对DFS思路很不清晰,总是做着做着就乱了,刷个水题找找思路。
题意:经典DFS,找出所有的能让1~n的数形成素数环的序列(相邻相加为素数);
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <cmath> 3 #include <cstdio> 4 #include <cstring> 5 #include <cstdlib> 6 #include <string> 7 #include <sstream> 8 #include <algorithm> 9 #define Max 2147483647 10 #define INF 0x7fffffff 11 #define ll long long 12 #define mem(a,b) memset(a,b,sizeof(a)) 13 #define repu(i, a, b) for(int i = (a); i < (b); i++) 14 const double PI=-acos(-1.0); 15 #define N 10010 16 using namespace std; 17 bool pri[N]; 18 int p[N]; 19 int prim() 20 { 21 memset(pri, true, sizeof(pri)); 22 for(int i = 2; i <= sqrt(60 +0.5); i++) 23 if(pri[i]) 24 for(int j = i << 1 ; j <= N; j += i) 25 pri[j] = false; 26 } 27 int n; 28 bool vis[N]; 29 void dfs(int pos,int m)///p[pos-1] = m 30 { 31 if(pos == n+1 && pri[p[n]+1]) 32 { 33 repu(i,1,n) 34 printf("%d ",p[i]); 35 printf("%d ",p[n]); 36 return ; 37 } 38 int i = 2; 39 repu(i,2,n+1) 40 { 41 if(pri[m + i] && !vis[i] )///符合条件 42 { 43 vis[i] = 1; 44 p[pos] = i; 45 dfs(pos+1,p[pos]); 46 vis[i] = 0; 47 } 48 } 49 } 50 int main() 51 { 52 //init(); 53 prim(); 54 memset(vis,0,sizeof(vis)); 55 int kase = 1; 56 while(~scanf("%d",&n)) 57 { 58 printf("Case %d: ",kase++); 59 p[1] = 1; 60 p[n+1] = 1; 61 dfs(2,1); 62 if(kase) 63 printf(" "); 64 } 65 return 0; 66 }