题目链接:https://codeforces.com/problemset/problem/366/C
题意:给定n个物品,每个物品都有一个美味值和卡路里值,从其中选出若干个使得成立,求成立的方案中,美味值的最大值。
分析:先把式子化简得(a[i] - k * b[i]), 设f[i][j]为前i个物品中获得美味值与卡路里值得差值为j得美味值max,显然f[i][j] = max(f[i - 1][j], f[i - 1][j - (a[i] - k * b[i])] + a[i]);
值得一提的是j - (a[i] - k * b[i])可能为负数,所以我们需要让其整体往右+100000即可,目标状态则为f[n][100000].
代码:
#include <bits/stdc++.h>
#define ios ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
#define x first
#define y second
#define endl '\n'
using namespace std;
typedef pair<int, int> PII;
const int N = 1e3 + 10;
const int M = 2e5 + 10;
const int INF = 0x3f3f3f3f;
const double INFF = 0x7f7f7f7f7f7f7f7f;
const int mod = 1e9 + 7;
int n, k;
int a[N], b[N];
int f[105][N * 200];
signed main()
{
ios;
cin >> n >> k;
for (int i = 1; i <= n; i++)
cin >> a[i];
for (int i = 1; i <= n; i++)
cin >> b[i];
memset(f, -0x3f, sizeof(f));
f[0][100000] = 0;
for (int i = 1; i <= n; i++)
{
for (int j = 0; j <= 200000; j++)
{
if(j - (a[i] - k * b[i]) >= 0)
f[i][j] = max(f[i - 1][j], f[i - 1][j - (a[i] - k * b[i])] + a[i]);
}
}
int ans = f[n][100000];
if (ans == 0)
ans = -1;
cout << ans << endl;
return 0;
}