#include<iostream>
#include<string>
#include<fstream>
using namespace std;
static int target, n;
static int result;
static int digit[8];
static int instant[8];
static int solution[8];
static int p;
static int splits;
static int mmax;
//#define DEBUG
static void search_dfs(int exist, int cur, int sum)
{
if (sum > target)
return;
if (cur >= n)
{
if (sum == mmax)
{
result++;
// target = -1;
}
else if (sum > mmax)
{
mmax = sum;
int i;
splits = p; result = 1;
for (i = 0; i < p; i++)
{
solution[i] = instant[i];
}
}
}
else
{
int tmp = exist * 10 + digit[cur]; // if tmp > target ?
instant[p++] = tmp;
search_dfs(0, cur + 1, sum + tmp);
instant[p--] = 0;
if (cur < n - 1)
search_dfs(tmp, cur + 1, sum);
}
}
int main()
{
#ifdef DEBUG
fstream cin("G:\\book\\algorithms\\acm\\Debug\\dat.txt");
#endif
string text;
while (cin >> target >> text)
{
if (target == 0 || text[0] == '0')
break;
int i;
n = text.length();
for (i = 0; i < n; i++)
{
digit[i] = text[i] - '0';
}
mmax = -1;
splits = 0;
p = 0;
result = 0;
search_dfs(0, 0, 0);
if (result == 1)
{
cout << mmax << " ";
for (i = 0; i < splits; i++)
cout << solution[i] << " ";
cout << "\n";
}
if (result > 1)
cout << "rejected" << "\n";
if (result == 0)
cout << "error" << "\n";
}
return 0;
}
输入 target, num要求对num做分割,分割成为多个数a1, a2, ...。这些数字之和sum,要满足 sum <= target 并且和target最接近。target, num最多是6位的10进制数。该题使用深度搜索,并且需要给出解的构成,可以作为同类题目的一个范例程序。
使用max,POJ编译不通过。
F:\temp\12041220.269501\Main.cpp(25) : error C2872: 'max' : ambiguous symbol
could be 'F:\temp\12041220.269501\Main.cpp(14) : int max'
估计是和C库中的符号相同了。
使用深度优先搜索,做了一个剪枝
if (sum > target)
return;
理解递归的过程对于设计深度搜索很重要, 整个搜索空间是一个满二叉树(不进行剪枝的情况下)
1 2 3 4 6
1 2 3 46
1 2 34 6
1 2 346
1 23 4 6
1 23 46
1 234 6
1 2346
12 3 4 6
12 3 46
12 34 6
12 346
123 4 6
123 46
1234 6
12346