#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int S, N;
cin >> S >> N;
vector<long long> dp(S + 1, 0);
for (int idx = 0; idx < N; idx++) {
long long V;
int W, K;
cin >> V >> W >> K;
if (W > S) continue;
K = min(K, S / W);
// If K is small, use binary representation
if (K <= 20) {
for (int cnt = 1; K > 0; cnt *= 2) {
int take = min(cnt, K);
int weight = W * take;
long long value = V * take;
for (int w = S; w >= weight; w--) {
dp[w] = max(dp[w], dp[w - weight] + value);
}
K -= take;
}
}
// If K is large, use monotonic deque optimization
else {
vector<long long> ndp = dp;
for (int rem = 0; rem < W; rem++) {
deque<pair<int, long long>> dq;
for (int j = 0; j * W + rem <= S; j++) {
int pos = j * W + rem;
long long val = dp[pos] - (long long)j * V;
while (!dq.empty() && dq.back().second <= val) {
dq.pop_back();
}
dq.push_back({j, val});
while (!dq.empty() && dq.front().first < j - K) {
dq.pop_front();
}
ndp[pos] = dq.front().second + (long long)j * V;
}
}
dp = ndp;
}
}
cout << dp[S] << '\n';
return 0;
}
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |