Codeforces Round #214 (Div. 2) C. Dima and Salad 01背包变形

原题链接:https://codeforces.ml/problemset/problem/366/C

题意

有n件物品,每个物品有价值ai,有容量bi,问如何取使得取得物品的总价值是总容量的k倍,求出最大的价值

分析

转化一下题意,我么可以把容量*k,变成求 ∑ a i = ∑ b i ∗ k \sum ai =\sum bi*k ai=bik,移动一下式子变成 b i = a i − b i ∗ k bi = ai-bi*k bi=aibik,最后我们求 ∑ b i \sum bi bi答案恰好是0时,最大的 ∑ a i \sum ai ai是多少,这不就是01背包的裸题吗,只不过容量可以出现负数,我们直接给背包的下限加上1e5,即[0,2e5]的容量范围。

Code

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <cmath>
#include <bitset>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <unordered_map>

using namespace std;
#define fi first
#define se second
#define re register
typedef long long ll;
typedef pair<ll, ll> PII;
typedef unsigned long long ull;
const int N = 2e5 + 10, M = 1e6 + 5, INF = 0x3f3f3f3f;
const int MOD = 1e9 + 7;
int a[N], b[N];
int dp[105][N];
void solve() {
    int n, m; cin >> n >> m;
    for (int i = 1; i <= n; i++) cin >> a[i];
    for (int i = 1; i <= n; i++) cin >> b[i], b[i] = a[i] - b[i] * m;
    memset(dp, -INF, sizeof dp);
    dp[0][100000] = 0;
    for (int i = 1; i <= n; i++) {
        for (int j = 0; j <= 2e5; j++) {
            if (j - b[i] <= 2e5 && j - b[i] >= 0)
                dp[i][j] = max(dp[i-1][j], dp[i-1][j - b[i]] + a[i]);
        }
    }
    if (dp[n][100000] == 0) cout << -1 << endl;
    else cout << dp[n][100000] << endl;
}

signed main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
#ifdef ACM_LOCAL
    freopen("input", "r", stdin);
    freopen("output", "w", stdout);
#endif
    solve();
    return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值