yeskendir_sultanov

Knapsack restoring answer

Feb 9th, 2025
15
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.18 KB | Source Code | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. #define ll long long
  4. #define pb push_back
  5. #define f first
  6. #define s second
  7. #define mp make_pair
  8.  
  9. using namespace std;
  10.  
  11. const int maxn = 1e2 + 5;
  12. const int maxs = 1e5 + 5;
  13.  
  14. int n, m[maxn], c[maxn], M;
  15. int dp[105][10005], p[105][10005];
  16. bool used[10005];
  17.  
  18. int main() {
  19.     freopen("input.txt", "r", stdin);
  20.     freopen("output.txt", "w", stdout);
  21.     cin >> n >> M;
  22.     for (int i = 1; i <= n; ++i)
  23.         cin >> m[i];
  24.     for (int i = 1; i <= n; ++i)
  25.         cin >> c[i];
  26.  
  27.     used[0] = true;
  28.     dp[0][0] = 0;
  29.  
  30.     for (int i = 1; i <= n; ++i)
  31.         for (int sum = M; sum >= 0; --sum) {
  32.             dp[i][sum] = dp[i - 1][sum];   
  33.             p[i][sum] = p[i - 1][sum];
  34.  
  35.             int x = sum - m[i];
  36.  
  37.             if (x >= 0 && dp[i][sum] < dp[i - 1][x] + c[i]) {
  38.                 dp[i][sum] = dp[i - 1][x] + c[i];
  39.                 p[i][sum] = i;
  40.             }
  41.         }
  42.  
  43.     int mx = 0, s = -1;
  44.  
  45.     for (int sum = M; sum >= 0; --sum)
  46.         if (dp[n][sum] > mx) {
  47.             mx = dp[n][sum];
  48.             s = sum;
  49.         }
  50.  
  51.     int sum = s;
  52.  
  53.     vector < int > ans;
  54.  
  55.     for (int i = n; i >= 1; --i) {
  56.         int j = p[i][sum];
  57.         if (i == j) {
  58.             ans.pb(i);
  59.             sum -= m[i];
  60.         }
  61.     }
  62.  
  63.     for (int i = 0; i < ans.size(); ++i)   
  64.         cout << ans[i] << endl;
  65.    
  66.     return 0;
  67. }
  68.  
Add Comment
Please, Sign In to add comment