当前位置:   article > 正文

划分型dp,CF 1935C - Messenger in MAC

划分型dp,CF 1935C - Messenger in MAC

一、题目

1、题目描述

2、输入输出

2.1输入

2.2输出

3、原题链接

1935C - Messenger in MAC


二、解题报告

1、思路分析

比较简单的思路是反悔贪心,这里不展开说了,来说一下dp的做法

由于式子里面带绝对值,很烦,我们将pair按照b升序排序,那么原式就变为

sum(a) + max(b) - min(b)

我们定义状态f(i, j) 为 前 i  个数 选了 j  个数 且以 (a[i], b[i]) 结尾,即第 i 个 数必选的最小 sum(a) - min(b) 的花费,这样定义是因为第 i 个数必选,那么max(b) 一定是 b[i]

则 f(i + 1, j + 1) = min(f(k, j)) + a[i]

枚举  k的话就变成了O(N^3),考虑维护前缀最小值,可以优化到O(N^2)

滚动数组优化又可以优化空间到O(N)

2、复杂度

时间复杂度: O(N^2)空间复杂度:O(N)

3、代码详解

 ​
  1. #include <bits/stdc++.h>
  2. #define sc scanf
  3. using i64 = long long;
  4. using i128 = __int128;
  5. using PII = std::pair<int, int>;
  6. constexpr int inf32 = 1e9 + 7;
  7. constexpr i64 inf64 = 1e18 + 7;
  8. constexpr int P = 998244353;
  9. constexpr double eps = 1e-6;
  10. // #define DEBUG
  11. void solve()
  12. {
  13. int n, L;
  14. std::cin >> n >> L;
  15. std::vector<int> a(n), b(n);
  16. for (int i = 0; i < n; ++ i) std::cin >> a[i] >> b[i];
  17. std::vector<int> p(n);
  18. std::iota(p.begin(), p.end(), 0);
  19. std::sort(p.begin(), p.end(), [&b](int i, int j) {
  20. return b[i] < b[j];
  21. });
  22. int res = 0;
  23. std::vector<i64> f(n + 1, inf64);
  24. for (int k = 0; k < n; ++ k) {
  25. int i = p[k];
  26. for (int j = k + 1; j; -- j) {
  27. f[j + 1] = std::min(f[j + 1], f[j] + a[i]);
  28. if (f[j] + b[i] + a[i] <= L)
  29. res = std::max(res, j + 1);
  30. }
  31. f[1] = std::min<i64>(f[1], a[i] - b[i]);
  32. if (a[i] <= L) res = std::max(res, 1);
  33. }
  34. std::cout << res << '\n';
  35. }
  36. int main()
  37. {
  38. #ifdef DEBUG
  39. freopen("in.txt", "r", stdin);
  40. freopen("out.txt", "w", stdout);
  41. #endif
  42. std::ios::sync_with_stdio(false), std::cin.tie(nullptr), std::cout.tie(nullptr);
  43. int _ = 1;
  44. std::cin >> _;
  45. while (_--)
  46. solve();
  47. return 0;
  48. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/代码探险家/article/detail/899695
推荐阅读
相关标签
  

闽ICP备14008679号