#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define MAXV 200001
#define MAXN 11
int dp[MAXV], val[MAXN], cnt[MAXN];
void zero_one_knapsack(int max_v, int v)
{
for(int i = max_v; i >= v; i --) {
if( dp[i-v] ) {
dp[i] = 1;
}
}
}
void complete_knapsack(int max_v, int v)
{
for(int i = 0; i <= max_v-v; i ++) {
if( dp[i] ) {
dp[i+v] = 1;
}
}
}
int knapsack(int max_v, int n)
{
int binary, tot;
memset(dp, 0, sizeof(dp)); dp[0] = 1;
for(int i = 0; i < n; i ++) {
if( val[i]*cnt[i] >= max_v ) {
complete_knapsack(max_v, val[i]);
}
else {
binary = 1; tot = cnt[i];
while( binary < tot ) {
zero_one_knapsack(max_v, val[i]*binary);
tot -= binary; binary <<= 1;
}
zero_one_knapsack(max_v, tot*val[i]);
}
}
for(int i = max_v; i >= 0; i --) {
if( dp[i] ) {
return i;
}
}
}
int main(int argc, char const *argv[])
{
#ifndef ONLINE_JUDGE
freopen("test.in", "r", stdin);
#endif
int max_v, n;
while( ~scanf("%d %d", &max_v, &n) ) {
for(int i = 0; i < n; i ++) {
scanf("%d %d", &cnt[i], &val[i]);
}
printf("%d\n", knapsack(max_v, n));
}
return 0;
}poj_1276
最新推荐文章于 2021-09-01 00:54:47 发布
本文深入探讨了零一背包与完全背包算法的实现细节,并通过实例展示了这两种算法在解决实际问题中的应用。
526

被折叠的 条评论
为什么被折叠?



