题目大意:给出N个单词的花费和价值,问在最多花费M的情况,能得到的最大价值
解题思路:因为花费和价值都在[0,10],所以将其压缩,不然的话,N太大了,直接背包会超时
接着就是完全背包问题了
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 10010;
int num[12][12];
int dp[N];
int n, m;
void init() {
memset(num, 0, sizeof(num));
char str[20];
int V, C;
for (int i = 0; i < n; i++) {
scanf("%s%d%d", str, &V, &C);
num[V][C]++;
}
}
void CompletePack(int val, int cost) {
for (int i = cost; i <= m; i++)
dp[i] = max(dp[i], dp[i - cost] + val);
}
void ZeroOnePack(int val, int cost) {
for (int i = m; i >= cost; i--)
dp[i] = max(dp[i], dp[i - cost] + val);
}
void solve() {
memset(dp, 0, sizeof(dp));
for (int i = 0; i <= 10; i++)
for (int j = 0; j <= 10; j++) {
if (num[i][j] * j >= m) CompletePack(i, j);
else {
int t = 1;
while (t <= num[i][j]) {
ZeroOnePack(i * t, j * t);
num[i][j] -= t;
t *= 2;
}
if (num[i][j])
ZeroOnePack(num[i][j] * i, j * num[i][j]);
}
}
int ans = 0;
for (int i = 0; i <= m; i++)
ans = max(ans, dp[i]);
printf("%d\n", ans);
}
int main() {
while (scanf("%d%d", &n, &m) != EOF) {
init();
solve();
}
return 0;
}