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 "books.h"
#include <bits/stdc++.h>
#define N 1000005
using namespace std;
typedef long long ll;
int G[N], ok[N], cor, sz[N], C[N], qtd_trivial = 0;
bool trivial[N];
int pref[N];
void dfs(int x)
{
if(ok[G[x]]) return;
ok[G[x]] = 1;
dfs(G[x]);
}
void co(int x)
{
if(C[G[x]]) return;
C[G[x]] = cor, sz[cor] ++;
co(G[x]);
}
ll minimum_walk(vector<int> p, int s)
{
int n = p.size();
ll ans = 0;
for(int i = 0; i < n; i++)
{
G[i] = p[i];
ans += abs(i - p[i]);
if(i != p[i]) pref[min(i, p[i])] ++, pref[max(i, p[i]) + 1] --;
}
for(int i = 0; i < n; i++) pref[i] += pref[i - 1];
for(int i = 0; i < n; i++)
{
if(C[i]) continue;
++cor;
C[i] = cor;
sz[cor] = 1;
co(i);
}
for(int i = 0; i < n; i++)
if(sz[C[i]] == 1) trivial[i] = true;
for(int i = 0; i < n; i++)
{
if(trivial[i] && pref[i] > 0) qtd_trivial ++;
}
for(int i = n - 1; i >= 0; i--)
{
if(!trivial[i]) break;
qtd_trivial ++;
}
return ans + 2*(cor - qtd_trivial - 1);
}
# | 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... |