1. 程式人生 > >POJ 1276 Cash Machine

POJ 1276 Cash Machine

多重揹包可行性

 

#include<iostream>
#include<algorithm>
using namespace std;
const int maxn = 100000 + 10;
int dp[maxn], num[maxn], value[maxn];
int v;
void zeroOnePack(int cost, int value){
	for(int i = v; i >= cost; --i)
		dp[i] = max(dp[i], dp[i - cost] + value);
}
void completePack(int cost, int value){
	for(int i = cost; i <= v; ++i)
		dp[i] = max(dp[i], dp[i - cost] + value);
}
void multPack(int cost, int value, int num){
	if(cost*num >= v){
		completePack(cost, value);
		return;
	}
	int k = 1;
	while(k <= num){
		zeroOnePack(cost*k, value*k);
		num -= k;
		k<<=1;
	}
	zeroOnePack(num*cost, num*value);
}
int main(){
	int n;
	while(~scanf("%d%d", &v, &n)){
		for(int i = 0; i < n; i++)	scanf("%d%d", &num[i], &value[i]);
		fill(dp, dp + maxn, 0);
		for(int i = 0; i < n; ++i)
			multPack(value[i], value[i], num[i]);
		printf("%d\n", dp[v]);
	}
	return 0;
}