Update CMakeLists.txt
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
/*
|
||||
* 背包 DP:考虑前 i 个物品的最大价值,在仅有 t 容量的情况下。
|
||||
*/
|
||||
|
||||
#include <iostream>
|
||||
|
||||
using namespace std;
|
||||
|
||||
struct Item {
|
||||
int weight, value;
|
||||
};
|
||||
|
||||
constexpr int MAX_N = 105, MAX_CAPACITY = 1005;
|
||||
int capacity, n;
|
||||
Item items[MAX_N];
|
||||
int dp[MAX_N][MAX_CAPACITY];
|
||||
|
||||
void log_dp() {
|
||||
for (int i = 0; i <= n; i++) {
|
||||
for (int j = 0; j <= capacity; j++) {
|
||||
clog << dp[i][j] << "\t";
|
||||
}
|
||||
clog << endl;
|
||||
}
|
||||
}
|
||||
|
||||
void solve_dp() {
|
||||
for (int i = 0; i <= capacity; i++) { dp[0][i] = 0; }
|
||||
for (int i = 0; i <= n; i++) { dp[i][0] = 0; }
|
||||
for (int stop_item = 1; stop_item <= n; stop_item++) {
|
||||
for (int w = 1; w <= capacity; w++) {
|
||||
dp[stop_item][w] = dp[stop_item - 1][w];
|
||||
if (w >= items[stop_item - 1].weight) { // 负数
|
||||
dp[stop_item][w] =
|
||||
max(dp[stop_item][w],
|
||||
dp[stop_item - 1][w - items[stop_item - 1].weight] + items[stop_item - 1].value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
ios::sync_with_stdio(false);
|
||||
cin.tie(nullptr);
|
||||
|
||||
cin >> capacity >> n;
|
||||
for (int i = 0; i < n; i++) {
|
||||
cin >> items[i].weight >> items[i].value;
|
||||
}
|
||||
|
||||
solve_dp();
|
||||
log_dp();
|
||||
cout << dp[n][capacity] << endl;
|
||||
|
||||
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user