标签:
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 34609 Accepted Submission(s): 15327
这道题就是回溯暴力。 首先打出一个素数表, 然后DFS回溯判断即可。
#include<cstdio> #include<cstring> #include<algorithm> using namespace std; int is_prime(int x) { for(int i=2; i*i<=x; i++) if(x%i==0) return 0; return 1; } int n, A[50]; bool isp[50], vis[50]; void dfs(int cur) { if(cur==n&&isp[A[0]+A[n-1]]) { for(int i=0; i<n-1; i++) { printf("%d ", A[i]); } printf("%d\n", A[n-1]); } else for(int i=2; i<=n; i++) if(!vis[i]&&isp[i+A[cur-1]]) { A[cur] = i; vis[i] = 1; dfs(cur+1); vis[i]=0; } } int main() { int kase = 0; while(scanf("%d", &n)!=EOF) { printf("Case %d:\n", ++kase); for(int i=2; i<=n*2; i++) isp[i] = is_prime(i); memset(vis, 0, sizeof(vis)); A[0] = 1; dfs(1); printf("\n"); } return 0; }
HDU1016 Prime Ring Problem(DFS回溯)
标签:
原文地址:http://www.cnblogs.com/acm1314/p/4746979.html