51nod 1086 背包问题V2

https://www.51nod.com/onlineJudge/questionCode.html#!problemId=1086

1086 背包问题 V2

基准时间限制:1 秒 空间限制:131072 KB 分值: 40 难度:4级算法题

收藏

关注

有N种物品,每种物品的数量为C1,C2......Cn。从中任选若干件放在容量为W的背包里,每种物品的体积为W1,W2......Wn(Wi为整数),与之相对应的价值为P1,P2......Pn(Pi为整数)。求背包能够容纳的最大价值。

Input

第1行,2个整数,N和W中间用空格隔开。N为物品的种类,W为背包的容量。(1 <= N <= 100,1 <= W <= 50000)
第2 - N + 1行,每行3个整数,Wi,Pi和Ci分别是物品体积、价值和数量。(1 <= Wi, Pi <= 10000, 1 <= Ci <= 200)

Output

输出可以容纳的最大价值。

Input示例

3 6
2 2 5
3 3 8
1 4 1

Output示例

9

二进制优化背包,所有数都可以由1,2,4.....(n-2*i)<2*i  都可以有这些数表示;

#include<iostream>
#include<string.h>
#include<algorithm>
#include<queue>
#include<vector>
#define inf 0x3f3f3f3f
#define ll long long
#define maxn 1000005
const int mod=1e9+7;
using namespace std;
ll a[maxn];
ll dp[maxn];
ll W[maxn];
ll P[maxn];
int main()
{
	ll n,w;
	cin>>n>>w;
	int k=0;
	for(int i=0;i<n;i++)
	{
		int v,p,s;
		cin>>v>>p>>s;
		int t=1;
		while(s>0)
		{
			if(t<s)
			{
				W[k]=t*v;
				P[k]=t*p;
			}
			else
			{
				W[k]=s*v;
				P[k]=s*p;
			}
			s-=t;
			t=t*2;
			k++;
		}
	}
	for(int i=0;i<=k;i++)
	{
		for(int j=w;j>=W[i];j--)
		{
			dp[j]=max(dp[j],dp[j-W[i]]+P[i]);
		}
	}
	cout<<dp[w]<<endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41453511/article/details/81412396