POJ 1416 Shredding Company(DFS)
写的真慢。
1 #include <cstdio> 2 #include <cstring> 3 #include <cmath> 4 #include <string> 5 #include <map> 6 #include <algorithm> 7 #include <queue> 8 #include <vector> 9 using namespace std; 10 char str[101]; 11 int n,len,ans,o[101],a[101]; 12 int z; 13 void dfs(int sum,int temp,int step) 14 { 15 int i; 16 if(sum+temp > n) 17 return ; 18 if(step == len) 19 { 20 if(sum + temp > ans) 21 { 22 ans = temp+sum; 23 for(i = 1;i <= len-1;i ++) 24 a[i] = o[i]; 25 z = 1; 26 } 27 else if(sum + temp == ans) 28 { 29 z ++; 30 } 31 return ; 32 } 33 o[step] = 1; 34 dfs(sum+temp,str[step]-'0',step+1); 35 o[step] = 0; 36 dfs(sum,temp*10+str[step]-'0',step+1); 37 } 38 int main() 39 { 40 int i,sum; 41 while(scanf("%d%s",&n,str)!=EOF) 42 { 43 ans = 0; 44 if(strcmp(str,"0") == 0&&n == 0) 45 break; 46 sum = 0; 47 z = 1; 48 len = strlen(str); 49 for(i = 0;i < len;i ++) 50 sum = sum + str[i] - '0'; 51 if(sum > n) 52 { 53 printf("error\n"); 54 continue; 55 } 56 dfs(0,str[0]-'0',1); 57 if(z > 1) 58 { 59 printf("rejected\n"); 60 continue; 61 } 62 printf("%d ",ans); 63 for(i = 0;i < len;i ++) 64 { 65 if(a[i]) printf(" "); 66 printf("%c",str[i]); 67 } 68 printf("\n"); 69 } 70 return 0; 71 }