This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
#define ll long long
#include "books.h"
#define sz(x) (int)x.size()
#define all(x) x.begin(), x.end()
#define ar array
using namespace std;
template<typename T> bool ckmin(T &a, const T &b) { return a > b ? a = b, 1 : 0; }
template<typename T> bool ckmax(T &a, const T &b) { return a < b ? a = b, 1 : 0; }
struct seg {
int N; vector<vector<ar<int, 2>>> adj;
seg(int n) : N(1<<(__lg(n)+1)), adj(2*N) {
for (int i = 2; i < 2*N; i++) adj[i].push_back({i >> 1, 0});
}
void add_edge(int x, int y) {
adj[x+N].push_back({y+N, 1});
}
void add_edge(int node, int nl, int nr, int ql, int qr, int x) { // l and r go to x
if (ql > nr || qr < nl) return;
if (ql <= nl && nr <= qr) {
adj[node].push_back({x + N, 0});
return;
}
int mid = (nl+nr)/2;
add_edge(node * 2, nl, mid, ql, qr, x);
add_edge(node * 2 + 1, mid + 1, nr, ql, qr, x);
}
void bfs(vector<int>& dist, vector<int> nodes) {
vector<int> dist2(2 * N, 1e9);
for (int i = 0; i < sz(dist); i++) dist2[i + N] = dist[i];
priority_queue<ar<int, 2>, vector<ar<int, 2>>, greater<ar<int, 2>>> q;
for (int v : nodes) q.push({dist[v], v + N});
while (q.size()) {
auto [cost, v] = q.top(); q.pop();
if (cost != dist2[v]) continue;
for (auto [u, w] : adj[v]) if (ckmin(dist2[u], cost + w)) q.push({dist2[u], u});
}
for (int i = 0; i < sz(dist); i++) dist[i] = dist2[i + N];
}
};
long long minimum_walk(std::vector<int> p, int s) {
int n = p.size();
{
int l = s, r = s;
for (int i = s; i >= 0; i--) if (i != p[i]) l = i;
for (int i = s; i < n; i++) if (i != p[i]) r = i;
p = vector<int>(p.begin() + l, p.begin() + r + 1);
n = r - l + 1;
}
seg st(n);
for (int i = 0; i < n; i++) {
if (i) st.add_edge(i, i-1);
if (i+1 < n) st.add_edge(i, i+1);
}
vector<bool> vis(n);
ll ans = 0;
for (int i = 0; i < n; i++) if (!vis[i]) {
int L = i, R = i, tmp = i;
vector<int> pth;
while (!vis[tmp]) {
ans += abs(tmp - p[tmp]);
ckmax(R, tmp), vis[tmp] = 1;
pth.emplace_back(tmp);
tmp = p[tmp];
}
for (int v : pth) st.add_edge(1, 0, st.N-1, L, R, v);
}
vector<int> d1(n, 1e9), d2(n, 1e9);
d1[0] = 0, d2[n-1] = 0;
st.bfs(d1, {0});
st.bfs(d2, {n-1});
vector<int> d3(n);
for (int i = 0; i < n; i++) d3[i] = d1[i] + d2[i];
vector<int> tot(n);
iota(all(tot), 0);
st.bfs(d3, tot);
return ans + 2 * d3[s];
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |