fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. const int N = 101;
  5. const int mx = 1e6+1;
  6. int n, S, a[N], dp[mx];
  7. // Gọi dp[i] là số giờ ít nhất để tạo thành số dinh dưỡng i
  8. // Bài toán quy về dạng dijsktra: Từ đỉnh u có thể đi đến các đỉnh v = u + a[i] (v <= S) với w = dp[u] + 1 + i
  9.  
  10. int main(){
  11. // icebear hehehhe
  12. // freopen("DOCTOR.inp", "r", stdin);
  13. // freopen("DOCTOR.out", "w", stdout);
  14. cin.tie(0) -> sync_with_stdio(0);
  15. cin >> n >> S;
  16. for(int i=1; i<=n; ++i) cin >> a[i];
  17. priority_queue<pair<int, int>> q;
  18. memset(dp, 0x3f, sizeof dp);
  19. q.push(make_pair(-1, 0));
  20. dp[0] = -1;
  21. while(!q.empty()){
  22. int du = q.top().first;
  23. int u = q.top().second;
  24. q.pop();
  25.  
  26. if (du != dp[u]) continue;
  27. if (u == S){
  28. cout << dp[u];
  29. exit(0);
  30. }
  31.  
  32. for(int i=1; i<=n; ++i){
  33. u += a[i];
  34. if (u > S) break;
  35. if (dp[u] > du + i + 1)
  36. q.push(make_pair(dp[u] = du + i + 1, u));
  37. }
  38. }
  39. cout << -1;
  40. return 0;
  41. }
  42.  
Success #stdin #stdout 0.01s 7476KB
stdin
5 12
1 4 2 6 3
stdout
6