二进制优化的多重背包
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define MAXN 101
#define MAXV 101
int dp[MAXV], p[MAXN], w[MAXN], c[MAXN];
void complete_knapsack(int max_v, int v, int w)
{
for(int i = 0; i <= max_v-v; i ++) {
if( dp[i+v] < dp[i]+w ) {
dp[i+v] = dp[i]+w;
}
}
}
void zero_one_knapsack(int max_v, int v, int w)
{
for(int i = max_v; i >= v; i --) {
if( dp[i-v]+w > dp[i] ) {
dp[i] = dp[i-v]+w;
}
}
}
int knapsack(int max_v, int n)
{
int binary, tot;
memset(dp, 0, sizeof(dp));
for(int i = 0; i < n; i ++) {
if( p[i]*c[i] >= max_v ) {
complete_knapsack(max_v, p[i], w[i]);
}
else {
binary = 1; tot = c[i];
while( binary < tot ) {
zero_one_knapsack(max_v, binary*p[i], binary*w[i]);
tot -= binary; binary <<= 1;
}
zero_one_knapsack(max_v, tot*p[i], tot*w[i]);
}
}
return dp[max_v];
}
int main(int argc, char const *argv[])
{
#ifndef ONLINE_JUDGE
freopen("test.in", "r", stdin);
#endif
int cas, max_v, n;
scanf("%d", &cas);
while( cas -- ) {
scanf("%d %d", &max_v, &n);
for(int i = 0; i < n; i ++) {
scanf("%d %d %d", &p[i], &w[i], &c[i]);
}
printf("%d\n", knapsack(max_v, n));
}
return 0;
}
hdu_2129
最新推荐文章于 2022-02-25 19:38:17 发布