Submission #990156

# Submission time Handle Problem Language Result Execution time Memory
990156 2024-05-29T17:31:53 Z tch1cherin K blocks (IZhO14_blocks) C++17
0 / 100
1 ms 348 KB
#include <bits/stdc++.h>
using namespace std;

const long long INF = 1e18;

struct dsu {
  vector<int> parent, rank;
  vector<long long> min_val;

  dsu(int n) : parent(n), rank(n, 1) {
    iota(parent.begin(), parent.end(), 0);
  }

  int get(int u) {
    return parent[u] == u ? u : (parent[u] = get(parent[u]));
  }

  void unite(int u, int v) {
    u = get(u), v = get(v);
    if (u != v) {
      if (rank[u] < rank[v]) {
        swap(u, v);
      }
      rank[u] += rank[v];
      parent[v] = u;
      min_val[u] = min(min_val[u], min_val[v]);
    }
  }
};

int main() {
  cin.tie(nullptr)->sync_with_stdio(false);
  int N, K;
  cin >> N >> K;
  vector<int> A(N);
  for (int &value : A) {
    cin >> value;
  }
  vector<int> stleft(N), stright(N);
  for (int i = 0; i < N; i++) {
    stleft[i] = i - 1;
    while (stleft[i] != -1 && A[stleft[i]] < A[i]) {
      stleft[i] = stleft[stleft[i]];
    }
  }
  for (int i = N - 1; i >= 0; i--) {
    stright[i] = i + 1;
    while (stright[i] != N && A[stright[i]] <= A[i]) {
      stright[i] = stright[stright[i]];
    }
  }
  vector<long long> dp(N + 1, INF), new_dp;
  dp[0] = 0;
  for (int k = 0; k < K; k++) {
    new_dp.assign(N + 1, INF);
    stack<int> st;
    dsu sets(N);
    sets.min_val = dp;
    multiset<long long> S;
    vector<vector<long long>> events(N + 1);
    for (int i = 0; i <= N; i++) {
      for (auto val : events[i]) {
        S.erase(S.find(val));
      }
      new_dp[i] = S.empty() ? INF : *S.begin();
      if (i == N) {
        continue;
      }
      while (!st.empty() && dp[st.top()] > dp[i]) {
        sets.unite(st.top(), i);
        st.pop();
      }
      long long val = sets.min_val[sets.get(stleft[i])] + A[i];
      S.insert(val);
      if (stright[i] < N) {
        events[stright[i] + 1].push_back(val);
      }
      st.push(i);
    }
    dp = new_dp;
  }
  cout << dp.back() << "\n";
}
# Verdict Execution time Memory Grader output
1 Correct 1 ms 344 KB Output is correct
2 Incorrect 0 ms 344 KB Output isn't correct
3 Halted 0 ms 0 KB -
# Verdict Execution time Memory Grader output
1 Correct 0 ms 348 KB Output is correct
2 Incorrect 0 ms 348 KB Output isn't correct
3 Halted 0 ms 0 KB -
# Verdict Execution time Memory Grader output
1 Correct 1 ms 344 KB Output is correct
2 Incorrect 0 ms 344 KB Output isn't correct
3 Halted 0 ms 0 KB -
# Verdict Execution time Memory Grader output
1 Correct 1 ms 344 KB Output is correct
2 Incorrect 0 ms 344 KB Output isn't correct
3 Halted 0 ms 0 KB -