Submission #297026

#TimeUsernameProblemLanguageResultExecution timeMemory
297026shayan_pAncient Books (IOI17_books)C++17
50 / 100
196 ms18808 KiB
#include<bits/stdc++.h>
#include "books.h"

#define F first
#define S second
#define PB push_back
#define sz(s) (int(s.size()))
#define bit(n, k) (((n)>>(k))&1)

using namespace std;

typedef long long ll;
typedef pair<int, int> pii;

const int maxn = 1e6 + 10;

int cnt[maxn];

ll minimum_walk(vector<int> p, int s){
    int n = sz(p);
    
    int MN = s, MX = s;
    ll ans = 0;
    for(int i = 0; i < n; i++){
	ans+= abs(p[i] - i);
	cnt[min(i, p[i])]++;
	cnt[max(i, p[i])]--;
    }
    int l = s, r = s;

    auto go = [&](){
		  while(true){
		      bool is = 0;
		      while(r < n && r <= MX){
			  MX = max(MX, p[r]);
			  r++;
			  is = 1;
		      }
		      while(l >= 0 && l >= MN){
			  MN = min(MN, p[l]);
			  l--;
			  is = 1;
		      }
		      if(!is)
			  break;
		  }
	      };
    int L = -1, R = n;
    int lst = -1;
    int sm = 0;
    for(int i = 0; i < n; i++){
	sm+= cnt[i];
	if(sm == 0){
	    if(i != n-1)
		ans+= 2;
	    if(lst < s && s <= i)
		L = lst, R = i+1;
	    lst = i;
	}	
    }

    go();
    while(L < l && r < R){
	ans+= 2;
	l--, r++;
	go();
    }
    for(int i = 0; i < s && p[i] == i; i++){
	ans-= 2;
    }
    for(int i = n-1; i > s && p[i] == i; i--){
	ans-= 2;
    }
    return ans;
}
#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...