递归_百炼 2803 碎纸机
1 #define _CRT_SECURE_NO_WARNINGS 2 #include <stdio.h> 3 #include <math.h> 4 #include <algorithm> 5 #include <stdlib.h> 6 #include <vector> 7 #include <map> 8 #include <queue> 9 #include <string> 10 #include <iostream> 11 #include <ctype.h> 12 #include <string.h> 13 #include <set> 14 #include <stack> 15 #include<functional> 16 using namespace std; 17 #define Size 10 18 #define maxn 1<<30 19 #define minn 1e-6 20 int ans[Size]; 21 int temp[Size]; 22 int a[Size]; 23 int targetNum; 24 char str[Size]; 25 int numLen; 26 int optimum; 27 int ansLen; 28 int reject = 0; 29 void solve(int total, int aPos, int tempPos){ 30 if (total > targetNum) return; 31 if (aPos == numLen){ 32 if (total == optimum) reject++; 33 if (total > optimum){ 34 optimum = total; 35 reject = 0; 36 for (int i = 0; i < tempPos; i++){ 37 ans[i] = temp[i]; 38 } 39 ansLen = tempPos; 40 } 41 return; 42 } 43 44 int assemble = 0; 45 for (int i = aPos; i < numLen; i++){ 46 assemble *= 10; 47 assemble += a[i]; 48 temp[tempPos] = assemble; 49 solve(total + assemble, i + 1, tempPos + 1); 50 } 51 } 52 void init(){ 53 optimum = 0; 54 } 55 int main(){ 56 while (cin >> targetNum ){ 57 if (targetNum == 0) break; 58 init(); 59 cin >> str; 60 int str2num = 0; 61 numLen = strlen(str); 62 int total = 0; 63 for (int i = 0; i < numLen; i++){ 64 str2num *= 10; 65 str2num += str[i] - '0'; 66 a[i] = str[i] - '0'; 67 total += a[i]; 68 } 69 if (str2num == targetNum) { 70 cout << str2num << " " << str2num << endl; 71 continue; 72 } 73 if (total > targetNum) { 74 cout << "error" << endl; 75 continue; 76 } 77 solve(0, 0, 0); 78 if (reject){ 79 cout << "rejected" << endl; 80 continue; 81 } 82 cout << optimum; 83 for (int i = 0; i < ansLen; i++) 84 cout << " " << ans[i]; 85 cout << endl; 86 } 87 return 0; 88 }