poj1276 多重背包

多重背包,套的1014的模板,链接http://blog.csdn.net/non_cease/article/details/6820068

#include <iostream>
using namespace std;

#define MAX(a, b) a>b?a:b
#define N 12
int dp[100005], amount[N], val[N], cash;
bool flag;

void ZeroOnePack(int c, int w)
{
	for(int v = cash; v >= c; v--)
        dp[v] = MAX(dp[v], dp[v-c]+w);
}

int main()
{
	int n, i, v;
    
	while(scanf("%d %d", &cash, &n) != EOF)
	{
		for(i = 1; i <= n; i++)
            scanf("%d %d", &amount[i], &val[i]);
		
		memset(dp, 0, sizeof(dp));
		for(i = 1; i <= n; i++)
		{
			if(amount[i] == 0) continue;
			
			if(amount[i]*val[i] >= cash) //完全背包
			{
				for(v = val[i]; v <= cash; v++)
					dp[v] = MAX(dp[v], dp[v-val[i]]+val[i]);
				continue;
			}
			
			int k = 1;
			while(k < amount[i])//二进制优化的01背包
			{
				ZeroOnePack(k*val[i], k*val[i]);
				amount[i] -= k;
				k *= 2;
			}
			ZeroOnePack(amount[i]*val[i], amount[i]*val[i]);
		}
		printf("%d\n", dp[cash]);
	}
	return 0;
}


 

阅读更多
文章标签: 优化 c
个人分类: DP
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭