Submission #1342539

#TimeUsernameProblemLanguageResultExecution timeMemory
1342539aykhnText editor (CEOI24_editor)C++20
0 / 100
2 ms580 KiB
#include <bits/stdc++.h>

using namespace std;

#define int long long
#define inf 0x3F3F3F3F3F3F3F3F

signed main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  int n;
  cin >> n;
  int x1, y1, x2, y2;
  cin >> x1 >> y1 >> x2 >> y2;
  x1--, y1--, x2--, y2--;
  int l[n];
  for (int &i : l) cin >> i;
  vector<array<int, 2>> adj[2 * n + 2];
  for (int i = 0; i < n; i++) {
    if (i - 1 >= 0) adj[2 * i].push_back({2 * (i - 1) + 1, 1}), adj[2 * (i - 1) + 1].push_back({2 * i, 1});
    if (i + 1 < n) adj[2 * i].push_back({2 * (i + 1), 1}), adj[2 * (i + 1)].push_back({2 * i, 1});
  }
  adj[2 * (n - 1)].push_back({2 * (n - 1) + 1, l[n - 1]});
  auto dist = [&](int x1, int y1, int x2, int y2) {
    return abs(x1 - x2) + abs(y1 - y2);
  };
  {
    vector<int> st;
    for (int i = 0; i < n; i++) {
      while (!st.empty() && l[st.back()] > l[i]) st.pop_back();
      if (!st.empty()) adj[2 * i + 1].push_back({2 * st.back() + 1, i - st.back()});
    }
  }{
    vector<int> st;
    for (int i = n - 1; i >= 0; i--) {
      while (!st.empty() && l[st.back()] > l[i]) st.pop_back();
      if (!st.empty()) adj[2 * i + 1].push_back({2 * st.back() + 1, st.back() - i});
    }
  }
  adj[2 * n].push_back({2 * x1, y1});
  for (int i = x1, mn = y1; i >= 0; i--) {
    mn = min(mn, l[i]);
    adj[2 * n].push_back({2 * i + 1, l[i] - mn + abs(i - x1)});
  }
  for (int i = x1, mn = y1; i < n; i++) {
    mn = min(mn, l[i]);
    adj[2 * n].push_back({2 * i + 1, l[i] - mn + abs(i - x1)});
  }
  adj[2 * x2].push_back({2 * n + 1, y2});
  for (int i = x2, mn = inf; i >= 0; i--) {
    mn = min(mn, l[i]);
    adj[2 * i + 1].push_back({2 * n + 1, abs(y2 - mn) + abs(i - x2)});
  }
  for (int i = x2, mn = inf; i < n; i++) {
    mn = min(mn, l[i]);
    adj[2 * i + 1].push_back({2 * n + 1, abs(y2 - mn) + abs(i - x2)});
  }
  for (int i = min(x1, x2), mn = inf; i <= max(x1, x2); i++) {
    mn = min(mn, l[i]);
    if (i == max(x1, x2) && min(y1, y2) <= mn) adj[2 * n].push_back({2 * n + 1, dist(x1, y1, x2, y2)});
  }
  priority_queue<array<int, 2>, vector<array<int, 2>>, greater<array<int, 2>>> pq;
  int dst[2 * n + 2];
  fill(dst, dst + 2 * n + 2, inf);
  dst[2 * n] = 0;
  pq.push({0, 2 * n});
  while (!pq.empty()) {
    auto [d, a] = pq.top();
    pq.pop();
    if (d > dst[a]) continue;
    for (auto &[v, w] : adj[a]) {
      if (dst[v] > d + w) {
        dst[v] = d + w;
        pq.push({dst[v], v});
      }
    }
  }
  cout << dst[2 * n + 1] << '\n';
}
#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...