题目链接:
[POJ 1416]Shredding Company[DFS]
题意分析:
给出数字a和字符串b。问:字符串b能否切割后,使得每个数字相加,和最接近a但不超过a,如果有多组解,输出"rejected",无解输出"error",输出最接近的那个数和切割方案。
解题思路:
字符串长度最多6。那么就枚举当前位是否切割,用vector记录切割位置,p代表当前访问的位,sum代表当前方案能得到的和。有这三个状态dfs即可。
个人感受:
看似麻烦,实则还好。
具体代码如下:
#include<algorithm>
#include<cctype>
#include<cmath>
#include<cstdio>
#include<cstring>
#include<iomanip>
#include<iostream>
#include<map>
#include<queue>
#include<set>
#include<sstream>
#include<stack>
#include<string>
#define ll long long
#define pr(x) cout << #x << " = " << (x) << '\n';
using namespace std;
const int INF = 0x7f7f7f7f;
const int MAXN = 1e6 + 111;
bool flag;
string b;
int ans, a;
vector<int> apos;
void dfs(int p, int sum, vector<int> pos) {
if (p == b.length()) {
int last = pos.back(), tsum = 0;
for (int i = last; i < p; ++i) {
tsum *= 10;
tsum += b[i] - '0';
}
sum += tsum;
if (sum <= a) {
if (sum > ans) {
ans = sum;
apos = pos;
flag = 0;
}
else if (sum == ans) {
flag = 1;
}
}
return;
}
// 不切
dfs(p + 1, sum, pos);
// 切
if (p != 0) {
int last = pos.back(), tsum = 0;
for (int i = last; i < p; ++i) {
tsum *= 10;
tsum += b[i] - '0';
}
pos.push_back(p);
dfs(p + 1, sum + tsum, pos);
}
return;
}
int main()
{
while (cin >> a >> b) {
if (a == 0 && b == "0") break;
ans = -1;
apos.clear();
vector<int> pos;
pos.push_back(0);
dfs(0, 0, pos);
if (ans == -1) cout << "error\n";
else if (flag) cout << "rejected\n";
else {
apos.push_back(b.length());
cout << ans;
for (int i = 1; i < apos.size(); ++i) {
cout << ' ';
for (int j = apos[i - 1]; j < apos[i]; ++j)
cout << b[j];
}
cout << '\n';
}
}
return 0;
}