【HDOJ】1258 Sum It Up
典型的深搜,剪枝的时候需要跳过曾经搜索过的相同的数目,既满足nums[i]=nums[i-1]&&visit[i-1]==0,visit[i-1]==0可以说明该点已经测试过。
1 #include <stdio.h> 2 #include <string.h> 3 4 #define MAXNUM 1005 5 6 int nums[MAXNUM]; 7 int visit[MAXNUM]; 8 int t, n; 9 10 void output() { 11 int i, j=0; 12 13 for (i=0; i<t; ++i) { 14 if (j && visit[i]) 15 printf("+%d", nums[i]); 16 if (j==0 && visit[i]) { 17 printf("%d", nums[i]); 18 j = 1; 19 } 20 } 21 printf("\n"); 22 } 23 24 int check(int index, int sum) { 25 if (index<0 || index>=t || visit[index] || sum+nums[index]>n) 26 return 0; 27 return 1; 28 } 29 30 int dfs(int beg, int sum) { 31 int i, val=0; 32 33 if (sum == n) { 34 output(); 35 return 1; 36 } 37 38 for (i=beg; i<t; ++i) { 39 if (i>beg && nums[i]==nums[i-1] && visit[i-1]==0) 40 continue; 41 if (check(i, sum)) { 42 visit[i] = 1; 43 if (dfs(i+1, sum+nums[i])) 44 val = 1; 45 visit[i] = 0; 46 } 47 } 48 49 return val; 50 } 51 52 int main() { 53 int i; 54 55 while (scanf("%d%d", &n, &t)!=EOF && (n||t)) { 56 for (i=0; i<t; ++i) 57 scanf("%d", &nums[i]); 58 memset(visit, 0, sizeof(visit)); 59 printf("Sums of %d:\n", n); 60 if ( !dfs(0, 0) ) 61 printf("NONE\n"); 62 } 63 return 0; 64 }