Submission #1292268

#TimeUsernameProblemLanguageResultExecution timeMemory
1292268hynmjKnapsack (NOI18_knapsack)C++20
100 / 100
44 ms3560 KiB
#include <bits/stdc++.h>
#define int long long
using namespace std;
const long long N = 2e5 + 5;
int a[N];
int dp[N]; // stands for maximum sum  if weight i
struct item
{
    int weight, value, quantity;
};
void solve()
{
    int n, s;
    cin >> s >> n;
    vector<item> a(n);
    int k = 1;
    for (int i = 0; i < n; i++)
    {
        cin >> a[i].value >> a[i].weight >> a[i].quantity;
        if (a[i].weight > s)
        {
            a[i].quantity = 0;
            continue;
        }
        a[i].quantity = min(a[i].quantity, s / a[i].weight);
    }
    sort(a.begin(), a.end(), [&](item a, item b)
         {if (a.weight ==b.weight)
            return a.value > b.value;
        return a.weight < b.weight; });
    // int cnt = 0;
    vector<item> b;
    int prev = -1;
    int cnt = 0;
    for (int i = 0; i < n; i++)
    {
        if (prev != a[i].weight)
        {
            cnt = 0;
            prev = a[i].weight;
        }
        while (cnt <= s / a[i].weight and a[i].quantity)
        {
            b.push_back(a[i]);
            a[i].quantity--;
            cnt++;
        }
    }

    for (auto j : b)
    {
        for (int i = s; i >= j.weight; i--)
        {
            dp[i] = max(dp[i], dp[i - j.weight] + j.value);
        }
    }
    int ans = 0;
    for (int i = 0; i <= s; ++i)
    {
        ans = max(ans, dp[i]);
    }
    cout << ans;
}

signed main()
{
    ios_base::sync_with_stdio(0);
    cin.tie(NULL);
    cout.tie(NULL);
    int t = 1;
    // cin >> t;
    for (int i = 1; i <= t; i++)
    {
        // cout << "Case #" << i << ':' << ' ';
        solve();
        cout << endl;
    }
    return 0;
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...