이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include <bits/stdc++.h>
using namespace std;
using i64 = long long;
#define UNSYNC ios::sync_with_stdio(false); cin.tie(nullptr);
#define all(x) x.begin(), x.end()
#define rep(i, ini, x) for (int i = ini; i < x; ++i)
#define per(i, fin, x) for (int i = fin; i >= x; --i)
int main() {
UNSYNC
int S, N; cin >> S >> N;
vector<vector<pair<int, int>>> data(S + 1); // To store items by weight
// Read each item's value V, weight W, and quantity K
rep(i, 0, N) {
int V, W, K; cin >> V >> W >> K;
data[W].push_back({V, K});
}
// Dynamic programming array to store maximum values up to weight S
vector<int> dp(S + 1, 0);
// Iterate over each possible weight
rep(i, 0, S + 1) {
if (!data[i].empty()) {
// Sort items at weight i by their values in descending order
sort(all(data[i]), [](const pair<int, int>& a, const pair<int, int>& b) {
return a.first > b.first;
});
// Try to use each item at this weight
int id = 0; // Index of the current item in data[i]
for (int j = 0; j * i <= S; ++j) {
if (id >= data[i].size()) break; // No more items to consider at this weight
// Update dp values for using current item up to its quantity
per(k, S, i) {
dp[k] = max(dp[k], dp[k - i] + data[i][id].first);
}
--data[i][id].second; // Use one unit of the current item
if (data[i][id].second == 0) ++id; // Move to next item if all units used
}
}
}
// Output the maximum value that can be put in a knapsack of capacity S
cout << dp[S] << '\n';
return 0;
}
컴파일 시 표준 에러 (stderr) 메시지
knapsack.cpp: In function 'int main()':
knapsack.cpp:36:24: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<std::pair<int, int> >::size_type' {aka 'long unsigned int'} [-Wsign-compare]
36 | if (id >= data[i].size()) break; // No more items to consider at this weight
| ~~~^~~~~~~~~~~~~~~~~
# | 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... |