Submission #1162839

#TimeUsernameProblemLanguageResultExecution timeMemory
1162839lopkusK blocks (IZhO14_blocks)C++20
0 / 100
1 ms328 KiB
#include <bits/stdc++.h>

using namespace std;

int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  int n, k;
  cin >> n >> k;
  vector<int64_t> a(n + 1);
  for(int i = 1; i <= n; i++) {
    cin >> a[i];
  }
  vector<vector<int64_t>> dp(n + 1, vector<int64_t>(k + 1));
  for(int i = 0; i <= n; i++) {
    for(int j = 0; j <= k; j++) {
      dp[i][j] = 1e18;
    }
  }
  dp[0][0] = 0;
  stack<int64_t> w;
  vector<int64_t> r(n + 1, n + 1);
  for(int i = n; i >= 1; i--) {
    while(!w.empty() && a[i] >= a[w.top()]) {
      w.pop();
    }
    if(!w.empty()) {
      r[i] = w.top();
    }
    w.push(i);
  }
  for(int c = 1; c <= k; c++) {
    stack<pair<int64_t, int64_t>> st, st1;
    for(int i = c; i <= n; i++) {
      while(!st.empty() && a[i] < (st.top()).first) {
        st.pop();
      }
      int64_t currentmin = 1e18;
      if(!st.empty()) {
        currentmin = (st.top()).second;
      }
      currentmin = min(currentmin, dp[i - 1][c - 1]);
      st.push({a[i], currentmin});
      while(!st1.empty() && ((st1.top()).second < i || (st1.top()).first > currentmin + a[i])) {
        st1.pop();
      }
      int64_t mn = currentmin + a[i];
      if(!st1.empty()) {
        mn = min(mn, (st1.top()).first);
      }
      dp[i][c] = mn;
      st1.push({currentmin + a[i], r[i] - 1});
    }
  }
  cout << dp[n][k];
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...