#include "books.h"
#include<bits/stdc++.h>
using ll = long long;
using namespace std;
const int maxn=1e6+10;
int n;
int mini[maxn];
int maxi[maxn];
bool bio[maxn];
int dsu[maxn],siz[maxn];
int cale(int a){return a==dsu[a] ? a:cale(dsu[a]);}
void join(int a,int b){
a=cale(a); b=cale(b);
if(siz[a]<siz[b]) swap(a,b);
dsu[a]=b;
siz[a]+=siz[b];
maxi[a]=max(maxi[a],maxi[b]);
mini[a]=min(mini[a],mini[b]);
}
void init(){
for(int i=0;i<n;i++){dsu[i]=i; siz[i]=1; maxi[i]=i; mini[i]=i;}
}
ll minimum_walk(vector<int> p, int s) {
n=p.size();
init();
ll ret=0;
int imal=n,imar=-1;
for(int i=0;i<n;i++){
if(p[i]!=i) imal=min(imal,i);
if(p[i]!=i) imar=i;
ret+=abs(p[i]-i);
if(bio[i]) continue;
int tren=i;
while(!bio[tren]){
bio[tren]=true;
join(tren,p[tren]);
tren=p[tren];
}
}
imal=min(imal,s);
imar=max(imar,s);
int l=s,r=s;
int tl=mini[cale(s)],tr=maxi[cale(s)];
int dodaol=0,dodaor=0;
while(l!=imal || r!=imar){
bool pl=false,pr=false;
if(l>imal && maxi[cale(l-1)]<=r){
pl=true;
l--;
if(l<tl){
ret+=2;
dodaol++;
}
tl=min(tl,mini[cale(l)]);
}
if(r<imar && mini[cale(r+1)]>=l){
pr=true;
r++;
if(r>tr){
ret+=2;
dodaor++;
}
tr=max(tr,maxi[cale(r)]);
}
if(pl || pr) continue;
ret-=2*max(dodaol,dodaor);
ret+=2;
dodaol=0;
dodaor=0;
}
return ret;
}
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
0 ms |
340 KB |
Output is correct |
2 |
Correct |
1 ms |
340 KB |
Output is correct |
3 |
Incorrect |
0 ms |
340 KB |
3rd lines differ - on the 1st token, expected: '8', found: '10' |
4 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
0 ms |
340 KB |
Output is correct |
2 |
Correct |
1 ms |
340 KB |
Output is correct |
3 |
Incorrect |
0 ms |
340 KB |
3rd lines differ - on the 1st token, expected: '8', found: '10' |
4 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
0 ms |
340 KB |
Output is correct |
2 |
Correct |
1 ms |
340 KB |
Output is correct |
3 |
Incorrect |
0 ms |
340 KB |
3rd lines differ - on the 1st token, expected: '8', found: '10' |
4 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
0 ms |
340 KB |
3rd lines differ - on the 1st token, expected: '3304', found: '4370' |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
0 ms |
340 KB |
Output is correct |
2 |
Correct |
1 ms |
340 KB |
Output is correct |
3 |
Incorrect |
0 ms |
340 KB |
3rd lines differ - on the 1st token, expected: '8', found: '10' |
4 |
Halted |
0 ms |
0 KB |
- |