ZOJ1213-Lumber Cutting—动态规划的实现

#include <stdio.h>
#include <memory.h>
#include <algorithm>
using namespace std;

struct stBoard
{
	int number, length;
	stBoard () {number = 1000;}	//木板数量的最优值,初值为∞
};

bool operator < (const stBoard &op1, const stBoard &op2)
{
	if(op1.number == op2.number)
		return op1.length > op2.length;
	return op1.number < op2.number;
}

int dp(int n, int board, int saw, int *part)
{
	stBoard plank[4096];
	plank[0].length = plank[0].number = 0;
	int count = (1 << n) - 1;
	for(int i = 0; i < count; i++)
		for(int j = 0; j < n; j++)
		{
			int index = i | 1 << j;	// 处理木料j
			if(index != i) // 木料j以前处理过
			{	
				stBoard now = plank[i];
				if(now.length >= part[j])
					//调整剩余木料的长度
					now.length -= part[j];
				else	//不能安排第i个木料
				{	//增加1个木料
					now.number++;
					now.length = board - part[j];
				}
				//调整剩余木料的长度
				now.length = max(now.length - saw, 0);
				//调整最优值
				plank[index] = min(plank[index], now);				
			}
		}
	return plank[count].number;
}


int main()
{
	printf("Problem 7 by team x\n");
	char c;
	int part[13];	//要切割的木料
	int board, saw;	//木板的长度,锯的宽度
	while(scanf("%d", &board) != EOF)	//读取木板的长度
	{	
		scanf("%d", &saw);				//读取木板的宽度
		int n = 0;			//木料的数量
		while((c = getc(stdin)) != '\n')//判断回车
		{	
			ungetc(c, stdin);	//将字符c退回缓冲区
			scanf("%d", part+n++);
		}
		printf("\n");
		printf("Board length            =%6d\n", board);
		printf("Saw width               =%6d\n", saw);
		printf("Number of boards needed =%6d\n", dp(n, board, saw, part));
	}
	printf("End of problem 7 by team x\n");
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值