之前做的一个方法是进行多重背包的基本算法 但是超时了 后来看了转换成01背包的方法 不是很理解 但是模板拿来直接用了 就可以过
在进行转换为01背包之后直接用01背包的算法
转换方法如下
cin >> a >> b; //a为当前物品的数量 b为当前物品的价值 在这道题道题目当中 当前物品的价值和消耗的容量应该是相同的
for(int j=1; j<=a; j*=2) //暂时不保存在现有的多重背包中 而是将其转换为经典的01背包 相应的数据存在数组w中
{
w[++cnt]=j*b;
a-=j;
}
if(a>0)
{
w[++cnt]=a*b;
} //完成向
详细的变换方法可以看背包九讲 http://wenku.baidu.com/view/885be370be1e650e52ea998f.html
完成ac代码如下
#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;
int dp[100005];
int w[1000];
int main()
{
int n,m,a,b,cnt;
while(cin >> n >> m) //总容量为n
{
cnt=0;
memset(dp,0,sizeof(dp));
memset(w,0,sizeof(w));
for(int i=1; i<=m; i++)
{
cin >> a >> b; //a为当前物品的数量 b为当前物品的价值 在这道题道题目当中 当前物品的价值和消耗的容量应该是相同的
for(int j=1; j<=a; j*=2) //暂时不保存在现有的多重背包中 而是将其转换为经典的01背包 相应的数据存在数组w中
{
w[++cnt]=j*b;
a-=j;
}
if(a>0)
{
w[++cnt]=a*b;
} //完成向
}
for(int i=1; i<=cnt; i++) //01背包的一维数组解法
for(int j=n; j>=w[i]; j--)
dp[j]=max(dp[j],dp[j-w[i]]+w[i]);
cout << dp[n] <<endl;
}
return 0;
}