Advertisement
tuki2501

nkleaves.cpp

Nov 9th, 2021
805
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.18 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. #define taskname "nkleaves"
  5.  
  6. void ioset() {
  7.   cin.tie(0)->sync_with_stdio(0);
  8.   if (fopen(taskname".INP", "r")) {
  9.     freopen(taskname".INP", "r", stdin );
  10.     freopen(taskname".OUT", "w", stdout);
  11.   }
  12. }
  13.  
  14. typedef long long ll;
  15.  
  16. const int N = 100005;
  17. const int M = 15;
  18. const ll INF = 1e18;
  19.  
  20. struct Line {
  21.   ll a, b;
  22.   Line() { a = 0; b = INF; }
  23.   Line(ll a, ll b): a(a), b(b) {}
  24.   ll operator()(ll x) { return a * x + b; }
  25. };
  26.  
  27. struct Node {
  28.   Line line;
  29.   Node *lef, *rig;
  30.   Node() { lef = rig = nullptr; }
  31. };
  32.  
  33. struct LCT {
  34.   Node *node;
  35.   LCT() { node = new Node; }
  36.   void insert(Node *&node, ll l, ll r, Line line) {
  37.     if (l > r) return;
  38.     if (node == nullptr) node = new Node;
  39.     if (l == r) {
  40.       if (line(l) < node->line(l)) node->line = line;
  41.       return;
  42.     }
  43.     ll m = (l + r) / 2;
  44.     if (line.a > node->line.a) swap(line, node->line);
  45.     if (line(m) < node->line(m)) {
  46.       swap(line, node->line);
  47.       insert(node->lef, l, m, line);
  48.     }
  49.     else insert(node->rig, m + 1, r, line);
  50.   }
  51.   ll query(Node *&node, ll l, ll r, ll x) {
  52.     if (l > r || node == nullptr) return INF;
  53.     if (l == r) return node->line(x);
  54.     ll m = (l + r) / 2;
  55.     if (x < m) return min(node->line(x), query(node->lef, l, m, x));
  56.     else return min(node->line(x), query(node->rig, m + 1, r, x));
  57.   }
  58.   void insert(Line line) {
  59.     insert(node, 1, 1e8, line);
  60.   }
  61.   ll query(ll x) {
  62.     return query(node, 1, 1e8, x);
  63.   }
  64. };
  65.  
  66. int n, m, a[N]; LCT lct[M];
  67. ll sum1[N], sum2[N], dp[N][M];
  68.  
  69. template<typename T>
  70. void chmin(T &a, T b) {
  71.   if (a > b) a = b;
  72. }
  73.  
  74. void solve() {
  75.   cin >> n >> m;
  76.   for (int i = 1; i <= n; i++) {
  77.     cin >> a[i];
  78.     sum1[i] = sum1[i - 1] + a[i];
  79.     sum2[i] = sum2[i - 1] + a[i] * i;
  80.   }
  81.   memset(dp, 0x3f, sizeof(dp));
  82.   for (int i = 1; i <= n; i++) {
  83.     for (int k = 1; k <= min(i, m); k++) {
  84.       if (k == 1) dp[i][k] = sum2[i] - sum1[i];
  85.       else dp[i][k] = lct[k - 1].query(sum1[i]) + sum2[i];
  86.       lct[k].insert(Line(-i, sum1[i - 1] * i - sum2[i - 1] + dp[i - 1][k]));
  87.     }
  88.   }
  89.   cout << dp[n][m] << '\n';
  90. }
  91.  
  92. signed main() {
  93.   ioset();
  94.   solve();
  95. }
  96.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement