POJ 1276 cash machine

分析:题目的意思是,给出需要的总金额和每种面值钱的数量,求能够获得的接近总金额的最大的金额。总金额0 <=cash <= 100000,所以背包的容量就是100000。而cost和weight都是面值D[k]。

又是一道多重背包的问题,毫无压力。写个代码练练手吧~

#include <iostream>
using namespace std;

int F[100001];
int n[11];
int D[11];

int max(int a, int b)
{
	return a>b?a:b;
}

void ZeroOnePack(int cost, int weight, int V)
{
	for (int v=V; v>=cost; --v)
		F[v] = max(F[v], F[v-cost]+weight);
}

void CompletePack(int cost, int weight, int V)
{
	for (int v=cost; v<=V; ++v)
		F[v] = max(F[v], F[v-cost]+weight);
}

void MultiPack(int cost, int weight, int V, int amount)
{
	if (cost*amount>=V) {
		CompletePack(cost, weight, V);
		return;
	}
	int k =1;
	while (k<amount) {
		ZeroOnePack(cost*k, cost*k, V);
		amount -= k;
		k *= 2;
	}
	ZeroOnePack(cost*amount, weight*amount, V);
}


int main(int argc, char **argv)
{
	int cash;
	int N;
	while (cin>>cash>>N) {
		for (int i=1; i<=N; ++i) {
			cin>>n[i]>>D[i];
		}
		memset(F, 0, sizeof(int)*100001);
		for (int i=1; i<=N; ++i)
			MultiPack(D[i], D[i], cash, n[i]);
		cout<<F[cash]<<endl;
	}
	system("pause");
	return 0;
}

47MS过,done!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值