fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4.  
  5. using namespace std;
  6.  
  7. int main() {
  8. // 1. Data Input Sesuai Kasus Anda
  9. const int N = 5; // Jumlah item
  10. const vector<int> W = {5, 4, 7, 8, 10}; // Bobot
  11. const vector<int> V = {10, 5, 7, 12, 8}; // Nilai
  12. const int C = 20; // Kapasitas
  13.  
  14. // 2. Inisialisasi Tabel DP
  15. // dp[w] = Nilai max untuk kapasitas 'w'
  16. vector<int> dp(C + 1, 0);
  17.  
  18. // 3. Algoritma Dynamic Programming
  19. for (int i = 0; i < N; i++) {
  20. int current_weight = W[i];
  21. int current_value = V[i];
  22.  
  23. // Iterasi kapasitas dari C ke current_weight (PENTING untuk 0/1 Knapsack)
  24. for (int w = C; w >= current_weight; w--) {
  25. // dp[w] = max(TIDAK diambil, diambil)
  26. dp[w] = max(dp[w], current_value + dp[w - current_weight]);
  27. }
  28. }
  29.  
  30. // 4. Output Hasil
  31. // Nilai maksimal berada di dp[C]
  32. cout << "Nilai Maksimal: " << dp[C] << endl;
  33.  
  34. return 0;
  35. }
Success #stdin #stdout 0.01s 5276KB
stdin
8
3 10 6 7 9 10 7 5
1 10 8 1 7 8 9 18
35
stdout
Nilai Maksimal: 29