标签:
6 8
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
简单的深度优先搜索题
源代码:
1 #include <iostream> 2 #include<cstring> 3 #include<cmath> 4 using namespace std; 5 int d[22]; 6 int a[22]; 7 int n,t=1; 8 9 int zs(int x) //判断是否为质数 10 { 11 for(int i=2;i<=(int)sqrt(x);i++) 12 if(x%i==0) 13 return 0; 14 return 1; 15 } 16 void dfs(int x,int cnt) 17 { 18 if(cnt==n) //打表输出 19 { 20 for(int i=0;i<n-1;i++) 21 cout<<a[i]<<" "; 22 cout<<a[n-1]<<endl; 23 } 24 if(cnt>n) 25 return; 26 for(int i=2;i<=n;i++) 27 if(!d[i]&&zs(i+x)) 28 { 29 if(cnt==n-1) 30 if(!zs(i+a[0])) //不要忘记判断最后一个数和第一个数 31 continue; 32 a[cnt]=i; 33 d[i]=1; //写入环中,标记为1 34 dfs(i,cnt+1); 35 d[i]=0; //不符合要求,重新标记为0 36 } 37 } 38 int main() 39 { 40 while(cin>>n) 41 { 42 memset(d,0,sizeof(d)); 43 a[0]=1; 44 d[1]=1; //第一个必定为1,不要忘记标记 45 cout<<"Case "<<t++<<":"<<endl; 46 dfs(1,1); 47 cout<<endl; 48 } 49 return 0; 50 }
标签:
原文地址:http://www.cnblogs.com/q-c-y/p/5414535.html