标签:
题目链接:
http://acm.nyist.edu.cn/JudgeOnline/problem.php?pid=488
深搜模板:
1 void dfs(int 当前状态) 2 { 3 if(当前状态为边界状态) 4 { 5 记录或输出 6 return; 7 } 8 for(i=0;i<n;i++) //横向遍历解答树所有子节点 9 { 10 //扩展出一个子状态。 11 修改了全局变量 12 if(子状态满足约束条件) 13 { 14 dfs(子状态) 15 } 16 恢复全局变量//回溯部分 17 } 18 }
未优化的代码:
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 #include <math.h> 5 #include <algorithm> 6 #include <iostream> 7 using namespace std; 8 9 int a[21]={1}; 10 bool visit[21]; 11 int n; 12 13 bool isprime(int x){ 14 int i; 15 for(i=2;i*i<=x;i++){ 16 if(x%i==0) 17 return false; 18 } 19 return true; 20 } 21 22 void DFS(int x){ 23 int i; 24 if(x==n-1){ 25 if(isprime(a[x]+1)){ 26 printf("1"); 27 for(i=1;i<n;i++) 28 printf(" %d",a[i]); 29 printf("\n"); 30 return ; 31 } 32 } 33 for(i=2;i<=n;i++){ 34 if(visit[i]==0&&isprime(a[x]+i)){ 35 visit[i]=1; 36 a[x+1]=i; 37 DFS(x+1); 38 visit[i]=0; 39 } 40 } 41 } 42 int main() 43 { 44 int i; 45 int Case=1; 46 while(scanf("%d",&n),n){ 47 memset(visit,0,sizeof(visit)); 48 printf("Case %d:\n",Case++); 49 if(n%2==0||n==1) 50 DFS(0); 51 else 52 printf("No Answer\n"); 53 } 54 return 0; 55 }
素数可以打表:
1 #include <iostream> 2 #include <algorithm> 3 using namespace std; 4 bool sushu[]={0, 5 0,1,1,0,1,0,1,0, 6 0,0,1,0,1,0,0,0, 7 1,0,1,0,0,0,1,0, 8 0,0,0,0,1,0,1,0, 9 0,0,0,0,1,0,1,0 10 }; 11 int a[21], res[21], n, flag; 12 void dfs(int now) 13 { 14 int i; 15 if (now==n&&sushu[a[n-1]+a[n]]) 16 { 17 flag = 0; 18 for (i = 0; i<n; i++) 19 cout<<a[i]<<" "; 20 cout<<endl; 21 } 22 else 23 { 24 for (i = 2; i<=n; i++) 25 if (!res[i]&&sushu[i+a[now-1]]) 26 { 27 res[i] = 1; 28 a[now] = i; 29 dfs(now+1); 30 res[i] = 0; 31 } 32 } 33 } 34 int main() 35 { 36 int N; 37 N=1; 38 while (cin>>n&&n) 39 { 40 flag = 1; 41 a[0]=a[n]=1; 42 cout<<"Case "<<N++<<":"<<endl; 43 if ((n-1)&1||n==1) 44 dfs(1); 45 if (flag) 46 cout<<"No Answer\n"; 47 } 48 return 0; 49 }
标签:
原文地址:http://www.cnblogs.com/wangmengmeng/p/4843380.html