Submission #515001

#TimeUsernameProblemLanguageResultExecution timeMemory
515001CrouchingDragonSafety (NOI18_safety)C++17
100 / 100
82 ms7588 KiB
#include <bits/stdc++.h>

template <typename T>
using minpq = std::priority_queue<T, std::vector<T>, std::greater<T>>;

template <typename T>
struct SlopeTrick {
  inline static const T inf = std::numeric_limits<int64_t>::max() / 2;
  T cost = 0, left_offset = 0, right_offset = 0;
  std::priority_queue<std::pair<T, T>> left;
  minpq<std::pair<T, T>> right;
  SlopeTrick() {
    left.emplace(-inf, 0);
    right.emplace(+inf, 0);
  }
  void add_left(T x, T slope) {
    right.emplace(x - right_offset, slope);
    while (slope > 0) {
      auto [y, s] = right.top();
      right.pop();
      y += right_offset;
      T take = std::min(slope, s);
      cost += take * (x - y);
      slope -= take;
      s -= take;
      left.emplace(y + left_offset, take);
      if (s) {
        right.emplace(y - right_offset, s);
      }
    }
  }
  void add_right(T x, T slope) {
    left.emplace(x + left_offset, slope);
    while (slope > 0) {
      auto [y, s] = left.top();
      left.pop();
      y -= left_offset;
      T take = std::min(slope, s);
      cost += take * (y - x);
      slope -= take;
      s -= take;
      right.emplace(y - right_offset, take);
      if (s) {
        left.emplace(y + left_offset, s);
      }
    }
  }
  void add_abs(T x, T slope) {
    add_left(x, slope);
    add_right(x, slope);
  }
  void relax_left(T offset) {
    left_offset += offset;
  }
  void relax_right(T offset) {
    right_offset += offset;
  }
  void relax(T offset) {
    relax_left(offset);
    relax_right(offset);
  }
};

constexpr int64_t inf = std::numeric_limits<int64_t>::max() / 2;

int main() {
  std::ios_base::sync_with_stdio(false);
  std::cin.tie(nullptr);
  int N, H;
  std::cin >> N >> H;
  std::vector<int> S(N);
  for (int i = 0; i < N; ++i) {
    std::cin >> S[i];
  }
  SlopeTrick<int64_t> st;
  for (int i = 0; i < N; ++i) {
    st.relax(H);
    st.add_abs(S[i], 1);
  }
  std::cout << st.cost << '\n';
  exit(0);
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...