Submission #1247965

#TimeUsernameProblemLanguageResultExecution timeMemory
1247965vuvietKnapsack (NOI18_knapsack)C++20
100 / 100
103 ms37304 KiB
/**
 *  __      __   __      __
 *  \ \    / /   \ \    / (_)     _____
 *   \ \  / /_   _\ \  / / _  ___|_   _|
 *    \ \/ /| | | |\ \/ / | |/ _ \ | |
 *     \  / | |_| | \  /  | |  __/ | |
 *      \/   \__,_|  \/   |_|\____||_|
 *
 *     Author:    VuViet
 *     Created:   2025-07-26 22:59
**/

#include <bits/stdc++.h>

using namespace std;

#define int long long
#define ____VuViet__ signed main

typedef pair<int, int> pii;
const int N = 1e5 + 5;
const int maxS = 2e3 + 2;
const int inf = 1e9 + 9;

int v[N], w[N], k[N], dp[maxS][maxS];
map<int, vector<pii>> m;
int S, n;

void ReadData()
{
    cin >> S >> n;
    for (int i = 1; i <= n; ++i)
    {
        cin >> v[i] >> w[i] >> k[i];
        m[w[i]].push_back({v[i], k[i]});
    }
}


void Solve()
{
    for (int i = 0; i <= S; ++i)
        for (int j = 0; j <= S; ++j)
            dp[i][j] = -inf;
    dp[0][0] = 0;
    int i = 1;
    for (auto [w, items] : m)
    {
        sort(items.rbegin(), items.rend());
        for (int j = 0; j <= S; ++j) 
        {
			dp[i][j] = dp[i - 1][j];
			int copies = 0, k = 0, used = 0, profit = 0;
			while ((copies + 1) * w <= j && k < items.size())
			{
				++copies;
				profit += items[k].first;
				if (dp[i - 1][j - copies * w] != -inf) {
					dp[i][j] = max(dp[i][j], dp[i - 1][j - copies * w] + profit);
				}
				++used;
				if (used == items[k].second) {
					used = 0, ++k;
				}
			}
		}
		++i;
    }
    int ans = 0;
    for (int j = 0; j <= S; ++j) 
        ans = max(ans, dp[i - 1][j]);
    cout << ans;
}

____VuViet__()
{
    ReadData();
    Solve();
    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...