1+ #include < iostream>
2+ #include < vector>
3+ #include < string>
4+
5+ using std::vector;
6+ using std::cin;
7+ using std::cout;
8+ using std::endl;
9+ using std::string;
10+
11+ // 1:Shredding Company
12+ // 将一串数字分割,使得分割后的数字和最接近 target(不大于)
13+ // 1. 如果数字正好等于target,则不会剪切
14+ // 2. 如果多种最接近target的方案,则输出 rejected
15+ // 3. 如果数字和大于target,则输出 error
16+ // 4. 否则输出sum和方案
17+
18+ int minDifference = 2147483647 ; // 与target的最小差
19+ int target = -1 ;
20+ int state = -1 ; // 状态 0->存在解决方案 1->重复 -1->无解决方案
21+ vector<int > tempSolution; // 临时存储解决方案
22+ vector<int > solution; // minDifference对应的解决方案
23+
24+ // divisor最多比num的长度多1
25+ bool divisorInNum (int num, int divisor) {
26+ if (num / divisor != 0 ) {
27+ return true ;
28+ }
29+
30+ if (num / divisor == 0 && num / (divisor / 10 ) != 0 ) {
31+ return true ;
32+ }
33+
34+ return false ;
35+ }
36+
37+ void dfs (int num, int difference) {
38+
39+ // 最优化剪枝
40+ if (difference - num > minDifference) {
41+ return ;
42+ }
43+ // 可行性剪枝
44+ if (difference < 0 || (difference == 0 && num != 0 )) {
45+ return ;
46+ }
47+ if (num == 0 ) {
48+ if (difference < minDifference) {
49+ state = 0 ;
50+ // 保存符合要求的解决方案
51+ minDifference = difference;
52+ solution = tempSolution;
53+ } else if (difference == minDifference) {
54+ state = 1 ;
55+ }
56+ return ;
57+ }
58+
59+ int divisor = 10 ;
60+ while (num != 0 && divisorInNum (num, divisor)) {
61+ int splitor = num % divisor;
62+ tempSolution.push_back (splitor);
63+ dfs (num / divisor, difference - splitor);
64+ // 回溯
65+ tempSolution.pop_back ();
66+ divisor *= 10 ;
67+ }
68+ }
69+
70+ int main (int argc, char *argv[]) {
71+ int num = -1 ;
72+ while (cin >> target >> num && target != 0 && num != 0 ) {
73+ minDifference = 2147483647 ;
74+ state = -1 ;
75+ if (num == target) {
76+ cout << num << ' ' << num << endl;
77+ } else {
78+ dfs (num, target);
79+ if (state == 0 ) {
80+ cout << target - minDifference;
81+ // 倒序遍历
82+ for (int i = solution.size () - 1 ; i >= 0 ; i--) {
83+ cout << " " << solution[i];
84+ }
85+ cout << endl;
86+ } else if (state == -1 ) {
87+ cout << " error" << endl;
88+ } else if (state == 1 ) {
89+ cout << " rejected" << endl;
90+ }
91+ }
92+ }
93+
94+ return 0 ;
95+ }
0 commit comments