poj_3260

/*
 * 我認為,首先求出能支付的錢的特定數目(多重背包)
 * 之後在上面的基礎上對找錢進行完全背包,即可解決
 * I think that first obtained the money can be paid a certain number (multiple backpack)
 * After completely backpack on the basis of the above, give change, can be solved
*/
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

#define MAXV	1200005
#define MAXN	101
#define INF		0x3f3f3f3f

int val[MAXN], cnt[MAXN], dp[MAXV];

void complete_knapsack(int max_v, int x, int step)
{
	for(int v = 0; v <= max_v-x; v ++) {
		if( INF != dp[v] ) {
			dp[v+x] = min(dp[v+x], dp[v]+step);
		}
	}
}

void zero_one_knapsack(int max_v, int x, int step)
{
	for(int v = max_v-x; v >= 0; v --) {
		if( INF != dp[v] ) {
			dp[v+x] = min(dp[v+x], dp[v]+step);
		}
	}
}

void special_knapsack(int max_v, int x, int step)
{
	for(int v = max_v; v >= x; v --) {
		if( INF != dp[v] ) {
			dp[v-x] = min(dp[v-x], dp[v]+step);
		}
	}
}

int dynamic_programming(int n, int ans)
{
	int binary, t_cnt, max_v(10000);
	fill(dp, dp+max_v+2, INF);	dp[0] = 0;
	for(int i = 0; i < n; i ++) {
		if( cnt[i]*val[i] >= max_v ) {
			complete_knapsack(max_v, val[i], 1);
		}
		else {
			binary = 1; t_cnt = cnt[i];
			while( binary < t_cnt ) {
				zero_one_knapsack(max_v, binary*val[i], binary);
				t_cnt -= binary;
				binary <<= 1;
			}
			zero_one_knapsack(max_v, t_cnt*val[i], t_cnt);
		}
	}
	for(int i = 0; i < n; i ++) {
		special_knapsack(max_v, val[i], 1);
	}
	return (INF == dp[ans])? -1 : dp[ans];
}

int main(int argc, char const *argv[])
{
#ifndef ONLINE_JUDGE
	freopen("test.in", "r", stdin);
#endif
	int n, max_v, ans;
	while( ~scanf("%d %d", &n, &ans) ) {
		for(int i = 0; i < n; i ++) {
			scanf("%d", &val[i]);
		}
		for(int i = 0; i < n; i ++) {
			scanf("%d", &cnt[i]);
		}
		printf("%d\n", dynamic_programming(n, ans));
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值