标签:
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1016
Prime Ring Problem
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
1 #include <iostream> 2 #include <cstring> 3 using namespace std; 4 5 #define maxn 40 6 int vis[21], x[21], T, n; 7 int prime[maxn] = { 1, 1, 0 }; 8 void init() 9 { 10 int i, j; 11 for (i = 2; i <= maxn; i++){ 12 if (!prime[i]){ 13 for (j = 2; i*j <= maxn; j++) 14 prime[i*j] = 1; 15 } 16 } 17 } 18 19 void dfs(int cur){ 20 if (cur == n&&!prime[1 + x[n - 1]]){ 21 for (int i = 0; i < n; i++){ 22 if (i) cout << ‘ ‘; 23 cout << x[i]; 24 } 25 cout << endl; 26 } 27 else for (int i = 2; i <= n; i++){ 28 if (!vis[i] && !prime[i + x[cur - 1]]){ 29 x[cur] = i; 30 vis[i] = 1; 31 dfs(cur + 1); 32 vis[i] = 0; 33 } 34 } 35 } 36 37 int main(){ 38 init(); 39 while (cin >> n){ 40 cout << "Case " << ++T << ‘:‘ << endl; 41 if (n == 1) 42 cout << 1 << endl; 43 else if (n & 1) 44 cout << endl; 45 else{ 46 memset(vis, 0, sizeof(vis)); 47 x[0] = 1; 48 dfs(1); 49 } 50 cout << endl;//没加这一句pe来个wa,我也是醉了,各种改,无爱了~~~~ 51 } 52 return 0; 53 }
[HDU 1016]--Prime Ring Problem(回溯)
标签:
原文地址:http://www.cnblogs.com/zyxStar/p/4592311.html