poj 2034(dfs)
读清题意,暴力dfs即可。
提醒下自己:不会时多试试暴力,可能会有意想不到的结果。。。。有时候不要太谨慎。。
1 // File Name: 2034.cpp 2 // Author: Missa_Chen 3 // Created Time: 2013年05月29日 星期三 19时27分06秒 4 5 #include<iostream> 6 #include<string> 7 #include<algorithm> 8 #include<cstdio> 9 #include<cstring> 10 #include<cmath> 11 #include<queue> 12 #include<map> 13 #include<stack> 14 #include<set> 15 #include<cstdlib> 16 17 using namespace std; 18 19 #define LL long long 20 const int inf = 0x3f3f3f3f; 21 const int maxn = 1e4 + 5; 22 int n, m, d; 23 int p[maxn], ans[maxn]; 24 void prime() 25 { 26 memset(p, 0, sizeof(p)); 27 p[0] = p[1] = 1; 28 for (int i = 2; i < maxn; ++i) 29 { 30 if (p[i]) continue; 31 for (int j = i << 1; j < maxn; j += i) 32 p[j] = 1; 33 } 34 } 35 bool f[maxn]; 36 int sum[11]; 37 bool dfs(int step) 38 { 39 for (int i = 2; i <= d; ++i) 40 if (step - 1 >= i && !p[sum[i]]) 41 return false; 42 if (step >= m - n + 2) return true; 43 for (int i = n; i <= m; ++i) 44 { 45 if (f[i]) continue; 46 for (int j = 2; j < step; ++j) 47 sum[j] -= ans[step - j]; 48 for (int j = 2; j <= d; ++j) 49 sum[j] += i; 50 ans[step] = i; 51 f[i] = 1; 52 if(dfs(step + 1)) return true; 53 for (int j = 2; j < step; ++j) 54 sum[j] += ans[step - j]; 55 for (int j = 2; j <= d; ++j) 56 sum[j] -= i; 57 f[i] = 0; 58 } 59 return false; 60 } 61 int main() 62 { 63 prime(); 64 while (~scanf("%d%d%d",&n,&m,&d)) 65 { 66 memset(f,0,sizeof(f)); 67 memset(sum,0,sizeof(sum)); 68 if (!n && !m && !d) break; 69 if (!dfs(1)) 70 { 71 puts("No anti-prime sequence exists."); 72 continue; 73 } 74 printf("%d",ans[1]); 75 for (int i = 2; i <= m - n + 1; ++i) 76 printf(",%d",ans[i]); 77 printf("\n"); 78 } 79 return 0; 80 }