HDU 1258 Sum It Up(DFS)
DFS在调了一会后搞了出来,发现不能输出重复的,我纠结啊,思前想后,想映射出来,效率高,可是实在想不出如何实现,存了数组吧,结果数据就是如此的水。。。0ms
1 #include <stdio.h> 2 #include <string.h> 3 int p[101],o[101],sum,n,z,num[501],k[501][101]; 4 void dfs(int x,int step,int s) 5 { 6 int i,j; 7 if(s == sum) 8 { 9 z ++; 10 num[z] = step-1; 11 for(i = 1;i <= z-1;i ++) 12 { 13 if(num[z] == num[i]) 14 { 15 for(j = 1;j <= num[z];j ++) 16 { 17 if(o[j] != k[i][j]) 18 break; 19 } 20 if(j == num[z]+1) 21 { 22 z--; 23 return ; 24 } 25 } 26 } 27 for(i = 1;i <= step-1;i ++) 28 { 29 k[z][i] = o[i]; 30 if(i == 1) 31 printf("%d",o[i]); 32 else 33 printf("+%d",o[i]); 34 } 35 printf("\n"); 36 return ; 37 } 38 if(x > n) 39 return ; 40 if(s > sum) 41 return ; 42 o[step] = p[x]; 43 dfs(x+1,step+1,s+p[x]); 44 dfs(x+1,step,s); 45 return ; 46 } 47 int main() 48 { 49 int i; 50 while(scanf("%d%d",&sum,&n)!=EOF) 51 { 52 memset(o,0,sizeof(o)); 53 if(sum == 0&&n == 0) 54 break; 55 z = 0; 56 for(i = 1;i <= n;i ++) 57 { 58 scanf("%d",&p[i]); 59 } 60 printf("Sums of %d:\n",sum); 61 dfs(1,1,0); 62 if(!z) 63 printf("NONE\n"); 64 } 65 return 0; 66 }