이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include "books.h"
#include <bits/stdc++.h>
#define pb push_back
#define x first
#define y second
#define all(a) a.begin(), a.end()
#define sz(a) (int)a.size()
#define rd() abs((int)rng())
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<int, int> pii;
const int maxn = 1e6 + 100;
const int mod = 1e9 + 7;
mt19937 rng(chrono::high_resolution_clock::now().time_since_epoch().count());
int n, s, val[maxn], nex, L[maxn], R[maxn], fr, to, prv[maxn], nxt[maxn];
ll base;
vector<int>p;
pii extend(int l, int r)
{
int cur_l = l, cur_r = r;
int i = l, j = r;
while(i >= cur_l || j <= cur_r)
{
if(i >= cur_l)
{
cur_l = min(cur_l, L[val[i]]);
cur_r = max(cur_r, R[val[i]]);
--i;
}
if(j <= cur_r)
{
cur_l = min(cur_l, L[val[j]]);
cur_r = max(cur_r, R[val[j]]);
j++;
}
}
return {cur_l, cur_r};
}
ll solve(int l, int r)
{
pii aa = extend(l, r);
int cur_l = aa.x, cur_r = aa.y;
if(cur_l <= fr && cur_r >= to)
return 0;
if(prv[cur_l] == -1)
{
if(cur_l > fr)
return 2 + solve(cur_l - 1, cur_r);
else
return 2 + solve(cur_l, cur_r + 1);
}
pii a = pii(cur_l, cur_r), b = pii(cur_l, cur_r);
int pr = prv[cur_l], nx = nxt[cur_r];
ll add1 = 0, add2 = 0;
while(a.x > pr)
a = extend(a.x - 1, a.y), add1 += 2;
while(b.y < nx)
b = extend(b.x, b.y + 1), add2 += 2;
if(add1 < add2)
return add1 + solve(a.x, a.y);
else
return add2 + solve(b.x, b.y);
}
ll minimum_walk(vector<int>perm, int S)
{
p = perm;
s = S;
n = sz(p);
for(int i = 1; i <= n; i++)
L[i] = mod, R[i] = -mod;
to = n - 1, fr = 0;
while(to >= 0 && p[to] == to)
--to;
while(fr < n && p[fr] == fr)
++fr;
if(fr > to)
return 0;
for(int i = 0; i < n; i++)
{
if(val[i] == 0)
{
int col = ++nex, cur = i;
while(val[cur] == 0)
{
val[cur] = col;
L[col] = min(L[col], cur);
R[col] = max(R[col], cur);
base += abs(p[cur] - cur);
cur = p[cur];
}
}
}
int pos = -1;
for(int i = 0; i <= s; i++)
{
prv[i] = pos;
if(R[val[i]] > s)
pos = i;
}
pos = -1;
for(int i = n - 1; i >= s; i--)
{
nxt[i] = pos;
if(L[val[i]] < s)
pos = i;
}
return base + solve(s, s);
}
/*int main()
{
ios_base::sync_with_stdio(false), cin.tie(0);
vector<int>perm;
ifstream fin("in.txt");
int n, s;
fin >> n >> s;
perm.resize(n);
for(int i = 0; i < n; i++)
fin >> perm[i];
cout << minimum_walk(perm, s) << endl;
return 0;
}*/
# | 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... |