제출 #408316

#제출 시각아이디문제언어결과실행 시간메모리
408316Kevin_Zhang_TWAncient Books (IOI17_books)C++17
50 / 100
192 ms22668 KiB
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define pb emplace_back
#define AI(i) begin(i), end(i)
template<class T> bool chmin(T &a, T b) { return b < a && (a = b, true); }
template<class T> bool chmax(T &a, T b) { return a < b && (a = b, true); }
#ifdef KEV
#define DE(args...) kout("[ " + string(#args) + " ] = ", args)
void kout() { cerr << endl; }
template<class T, class ...U> void kout(T a, U ...b) { cerr << a << ' ', kout(b...); }
template<class T> void debug(T l, T r) { while (l != r) cerr << *l << " \n"[next(l)==r], ++l; }
#else
#define DE(...) 0
#define debug(...) 0
#endif

const int MAX_N = 300010;

#include "books.h"

long long minimum_walk(std::vector<int> p, int s) {
	int n = p.size();
	vector<int> cntl(n+1), cntr(n+1);

	for (int i = 0;i < n;++i) {
		if (p[i] < i) 
			++cntl[p[i]+1], --cntl[i+1];
		if (p[i] > i)
			++cntr[i], --cntr[p[i]];
	}
	if (is_sorted(AI(p))) return 0;

	ll res = 0;

	for (int i = 1;i <= n;++i) {
		cntr[i] += cntr[i-1];
		cntl[i] += cntl[i-1];
	}

	int l = 0, r = n-1;
	while (p[l] == l) ++l;
	while (p[r] == r) --r;

	for (int i = l;i < r;++i) {
		res += max({cntl[i+1], cntr[i], 1}) * 2;
	}
//
	if (s > r) res += (s - r) * 2;
	if (s < l) res += (l - s) * 2;
	if (s <= r && s >= l) {
		int L = s, R = s;
		while (cntl[L]) --L;
		while (cntr[R]) ++R;
		int mn = s-l;

		int g = s;
		while (p[g] == g) ++g;
		chmin(mn, g - s);
		g = s;
		while (p[g] == g) --g;
		chmin(mn, s - g);

		res += mn * 2;
	}

	return 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...