【HDOJ】1539 Shredding Company
DFS。
1 /* 1539 */ 2 #include <iostream> 3 #include <cstdio> 4 #include <cstring> 5 #include <cstdlib> 6 #include <vector> 7 using namespace std; 8 9 #define INF 0xfffffff 10 11 int Q[105]; 12 char s[55]; 13 int ans; 14 int t, len; 15 bool flag; 16 vector<int> tb; 17 18 void dfs(int beg, int sum, int n) { 19 int i, j, k, tmp; 20 21 if (beg == len) { 22 if (sum<=t && sum>ans) { 23 tb.clear(); 24 for (i=0; i<n; ++i) 25 tb.push_back(Q[i]); 26 ans = sum; 27 flag = false; 28 n = 0; 29 } else if (sum == ans) { 30 flag = true; 31 } 32 return ; 33 } 34 35 for (i=beg; i<len; ++i) { 36 tmp = 0; 37 for (j=beg; j<=i; ++j) 38 tmp = 10*tmp+s[j]-'0'; 39 Q[n] = tmp; 40 dfs(i+1, sum+tmp, n+1); 41 } 42 } 43 44 int main() { 45 int i, j, k, tmp; 46 int sum; 47 48 #ifndef ONLINE_JUDGE 49 freopen("data.in", "r", stdin); 50 #endif 51 52 while (scanf("%d %s", &t, s) != EOF) { 53 if (t==0 && s[0]=='0' && s[1]=='\0') 54 break; 55 sum = 0; 56 tmp = 0; 57 for (i=0; s[i]; ++i) { 58 tmp = 10*tmp+s[i]-'0'; 59 sum += s[i]-'0'; 60 } 61 len = i; 62 if (sum > t) { 63 printf("error\n"); 64 continue; 65 } 66 if (tmp == t) { 67 printf("%d %s\n", t, s); 68 continue; 69 } 70 flag = false; 71 ans = -1; 72 tb.clear(); 73 dfs(0, 0, 0); 74 if (flag) { 75 printf("rejected\n"); 76 } else { 77 printf("%d", ans); 78 for (i=0; i<tb.size(); ++i) 79 printf(" %d", tb[i]); 80 printf("\n"); 81 } 82 } 83 84 return 0; 85 }