This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
#define nl '\n'
template <typename T>
inline bool ckmax(T& x, const T& y) {
  return x < y ? x = y, 1 : 0;
}
signed main() {
  std::ios::sync_with_stdio(false);
  std::cin.tie(nullptr);
  
  int S, N;
  std::cin >> S >> N;
  
  std::vector<std::map<int, int>> cnt(S + 1);
  for (int i = 0; i < N; i++) {
    int v, w, k;
    std::cin >> v >> w >> k;
    k = std::min(k, S / w);
    if (w <= S) {
      cnt[w][v] += k;
    }
  }
  std::vector<int> dp(S + 1);
  
  for (int i = 1; i <= S; i++) {
    int take_max = S / i;
    int sum = 0;
    for (auto& [v, k] : cnt[i]) {
      if (k >= 3) {
        int q = k - 1;
        k = 1 + (q & 1);
        if (2 * i <= S) {
          cnt[2 * i][2 * v] += q >> 1;
        }
      }
      sum += k;
    }
    for (auto [v, k] : cnt[i]) {
      if (sum - k <= take_max) {
        for (int x = 0; x < k; x++) {
          for (int j = S; j >= i; j--) {
            ckmax(dp[j], dp[j - i] + v);
          }
        }
      } 
      sum -= k;
    }
    // why wrong 
  }
  std::cout << dp[S] << nl;
}
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... |