fork download
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. typedef long long ll;
  6. typedef pair<int, int> ii;
  7.  
  8. const int INF = 1e9;
  9. const ll LINF = 1e18;
  10.  
  11. // dp knapsack
  12. // Biến thể: mỗi món vật có thể được chọn nhiều lần
  13.  
  14. const int N = 1e2 + 5;
  15. const int S = 1e6 + 5;
  16. const int MOD = 1e9 + 7;
  17.  
  18. void add(int& a, int b) {
  19. a += b;
  20. if (a >= MOD) a -= MOD;
  21. }
  22.  
  23. int n, s;
  24. int w[N];
  25. int dp[N][S]; // dp[i][j] = Số cách chọn các món vật trong i món vật đầu tiên sao cho tổng = j
  26. // (1 món có thể chọn nhiều lần)
  27.  
  28. int main() {
  29. ios::sync_with_stdio(false);
  30. cin.tie(nullptr);
  31. cin >> n >> s;
  32. for (int i = 1; i <= n; i++) cin >> w[i];
  33.  
  34. dp[0][0] = 1;
  35. for (int i = 1; i <= n; i++) {
  36. for (int j = 0; j <= s; j++) {
  37. // Bỏ qua món vật thứ i
  38. add(dp[i][j], dp[i - 1][j]);
  39. // Chọn món vật thứ i
  40. if (j >= w[i]) add(dp[i][j], dp[i][j - w[i]]);
  41. }
  42. } // O(n * s)
  43.  
  44. cout << dp[n][s] << '\n';
  45. }
Success #stdin #stdout 0s 5284KB
stdin
3 9
2 3 5
stdout
3