POJ 1416 碎纸机

博客介绍了如何解决POJ 1416问题,即对一个数字进行分割,使得分割后的数字之和不超过目标值并尽可能接近目标值。通过深度优先搜索算法进行求解,并实施了剪枝策略以优化搜索过程。整个搜索空间可视作一个满二叉树,在不剪枝的情况下。博客提供了具体的搜索路径示例,有助于理解和应用类似问题的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#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进制数。该题使用深度搜索,并且需要给出解的构成,可以作为同类题目的一个范例程序。

POJ1416

使用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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值