51nod-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

题解:典型的多重背包题目,对于某种物品,可以将其分解成,转变成01背包问题求解。但本题如此操作会T。我们注意到,对于多重背包中的任意一个具有C数量的物品,我们只需要将其范围(0 ~ C)都能取得即可,故我们可以进行二进制分解;

假设C = 1 + 2 + 4 + 。。。。 + 2 ^m + k(k < 2 ^(m + 1));那么只需要1 .. 2 .. 4 .....2^m..k这m + 1个数的随机组合即可获得0 ~ C内的任何一个数(1 .. 2 .. 4 .....2^m可以获得0到 2^(m + 1)内的任意数,加入k后下界不变,上界变成C)。使得复杂度从O(C * W * N)降为O(log(C) * W * N).

Ac代码

#include <stdio.h>
#include <iostream>
#include <string>
#include <queue>
#include <map>
#include <vector>
#include <algorithm>
#include <string.h>
#include <cmath>
 
using namespace std;

const int maxn = 55555;
int dp[maxn], num[maxn];

struct node{
	int w, p, c;
}p[111];

int main(){
	int n, w;
	scanf("%d%d", &n, &w);
	for(int i = 0; i < n; i++)
		scanf("%d %d %d", &p[i].w, &p[i].p, &p[i].c);
	for(int i = 0; i <= w; i++)
		dp[i] = 0;
	for(int i = 0; i < n; i++){
		for(int j = 0; j <= w; j++)
			num[j] = 0;
		int c = p[i].c;
		for(int j = 1; j < c; j <<= 1){
			for(int k = w; k - p[i].w * j >= 0; k--)
				dp[k] = max(dp[k], dp[k - p[i].w * j] + j * p[i].p);
			c -= j;
		}
		int j = c;
		for(int k = w; k - p[i].w * j >= 0; k--)
			dp[k] = max(dp[k], dp[k - p[i].w * j] + j * p[i].p);
		
	}
	printf("%d\n", dp[w]);
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/qq_37064135/article/details/80010603