Advertisement
Mirbek

Untitled

Jun 6th, 2022
675
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.39 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. const int N = 1e4 + 5;
  6. const int inf = 1e9 + 7;
  7.  
  8. int n, m, a[11], b[11], dp[11][N];
  9.  
  10. int main() {
  11.     for (int i = 0; i < 11; i++) {
  12.         for (int j = 0; j < N; j++) dp[i][j] = inf;
  13.     }
  14.  
  15.     cin >> n;
  16.  
  17.     dp[0][0] = 0;
  18.  
  19.     for (int i = 1; i <= n; i++) {
  20.         cin >> a[i] >> b[i];
  21.         for (int j = 0; j < N; j++) dp[i][j] = dp[i - 1][j];
  22.         for (int j = 1; j <= b[i]; j++) {
  23.             int num = j * a[i];
  24.             for (int k = N - 1; k >= num; k--) {
  25.                 dp[i][k] = min(dp[i][k], dp[i - 1][k - num] + j);
  26.             }
  27.         }
  28.     }
  29.  
  30.     cin >> m;
  31.  
  32.     while (m--) {
  33.         int x;
  34.         cin >> x;
  35.         if (dp[n][x] == inf) {
  36.             cout << "Impossible\n";
  37.             continue;
  38.         }
  39.         cout << dp[n][x] << " ";
  40.         int cnt = dp[n][x];
  41.  
  42.         for (int i = n; i >= 1; i--) {
  43.             for (int j = b[i]; j >= 1; j--) {
  44.                 int num = j * a[i];
  45.                 if (dp[i][x] == dp[i - 1][x - num] + j) {
  46.                     x -= num;
  47.                     while (j--) {
  48.                         if (--cnt)
  49.                             cout << a[i] << " ";
  50.                         else
  51.                             cout << a[i];
  52.                     }
  53.                     break;
  54.                 }
  55.             }
  56.         }
  57.  
  58.         cout << endl;
  59.     }
  60. }
  61.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement