Advertisement
Guest User

Untitled

a guest
Jan 25th, 2020
1,470
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.97 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. using ll = long long;
  4.  
  5. const int MW = 5001;
  6. int n, m;
  7. ll dp[2][MW];
  8. deque<int> dqs[MW];
  9.  
  10. int main() {
  11. ios_base::sync_with_stdio(false);
  12. cin.tie(NULL);
  13.  
  14. cin >> n >> m;
  15. for (int i = 0; i < n; i++) {
  16. ll num, cost, value;
  17. cin >> num >> cost >> value;
  18.  
  19. int pre = i & 1, cur = pre ^ 1;
  20. memset(dp[cur], 0, sizeof dp[cur]);
  21.  
  22. // comparison function for sliding window deque. Calculates the result of transition to dp[i] from dp[j]
  23. function<ll(int, int)> fun = [&] (int from, int to) {
  24. return dp[pre][from] + (to - from) / cost * value;
  25. };
  26.  
  27. // reset sliding window deque
  28. for (int j = 0; j < MW; j++)
  29. dqs[j].clear();
  30. dqs[0].push_back(0);
  31.  
  32. // do dynamic programming
  33. for (int j = 0; j < MW; j++) {
  34. // advance sliding window forwards
  35. auto &dq = dqs[j % cost];
  36. while (!dq.empty() && dq.front() < j - num * cost)
  37. dq.pop_front();
  38.  
  39. // update sliding window to include index j
  40. while (!dq.empty() && fun(dq.back(), j) < dp[pre][j])
  41. dq.pop_back();
  42. dq.push_back(j);
  43.  
  44. // do dp
  45. if (!dq.empty()) // take current type of item
  46. dp[cur][j] = fun(dq.front(), j);
  47. else // do not take current type of item
  48. dp[cur][j] = max(dp[cur][j], dp[pre][j]);
  49. }
  50. }
  51.  
  52. // answer queries
  53. int cur = ((n - 1) & 1) ^ 1; // final dp array
  54.  
  55. // sometimes its better to take less :)
  56. for (int i = 1; i < MW; i++)
  57. dp[cur][i] = max(dp[cur][i - 1], dp[cur][i]);
  58.  
  59. ll best = LLONG_MIN;
  60. for (int i = 0; i < m; i++) {
  61. int capacity, cost;
  62. cin >> capacity >> cost;
  63. best = max(best, dp[cur][capacity] - cost);
  64. }
  65. cout << best << '\n';
  66.  
  67. return 0;
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement