Submission #355340

#TimeUsernameProblemLanguageResultExecution timeMemory
355340KerimAncient Books (IOI17_books)C++17
100 / 100
249 ms77676 KiB
#include "books.h" #include "bits/stdc++.h" #define MAXN 1000009 #define INF 1000000007 #define mp(x,y) make_pair(x,y) #define all(v) v.begin(),v.end() #define pb(x) push_back(x) #define wr cout<<"----------------"<<endl; #define ppb() pop_back() #define tr(ii,c) for(__typeof((c).begin()) ii=(c).begin();ii!=(c).end();ii++) #define ff first #define ss second #define my_little_dodge 46 #define debug(x) cerr<< #x <<" = "<< x<<endl; using namespace std; typedef long long ll; typedef pair<int,int> PII; template<class T>bool umin(T& a,T b){if(a>b){a=b;return 1;}return 0;} template<class T>bool umax(T& a,T b){if(a<b){a=b;return 1;}return 0;} int L[MAXN],R[MAXN],bel[MAXN],S; int destL,destR; void extend(int &l,int &r){ int lp=l,rp=r; if(bel[l])umin(lp,L[bel[l]]),umax(rp,R[bel[l]]); if(bel[r])umin(lp,L[bel[r]]),umax(rp,R[bel[r]]); while(l!=lp or r!=rp){ if(l>lp and bel[--l])umin(lp,L[bel[l]]),umax(rp,R[bel[l]]); if(r<rp and bel[++r])umin(lp,L[bel[r]]),umax(rp,R[bel[r]]); } } int rec(int l,int r){ extend(l,r); if(l==destL and r==destR)return 0; if(l==destL)return rec(l,r+1)+2; if(r==destR)return rec(l-1,r)+2; int fl=l-1,fr=r;extend(fl,fr); int el=l,er=r+1;extend(el,er); int ans_l=1,ans_r=1; while(fl!=destL and fr<er){ ans_l++;fl--; extend(fl,fr); } if(fr<er)return ans_l*2+rec(fl,fr); fl=l,fr=r+1;extend(fl,fr); el=l-1,er=r;extend(el,er); while(fr!=destR and fl>el){ ans_r++;fr++; extend(fl,fr); } return min(ans_l,ans_r)*2+rec(fl,fr); } long long minimum_walk(vector<int> p, int s) { int n=int(p.size());vector<int>vis(n); destL=destR=s;ll res=0; for(int i=0;i<n;i++){ res+=abs(p[i]-i); if(p[i]!=i and !vis[i]){ int to=i;L[++S]=i; do{umax(R[S],to);bel[to]=S;vis[to]=1;to=p[to];}while(to!=i); umin(destL,L[S]);umax(destR,R[S]); } } return rec(s,s)+res; }
#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...