제출 #342742

#제출 시각아이디문제언어결과실행 시간메모리
342742cki86201Ancient Books (IOI17_books)C++11
50 / 100
270 ms27904 KiB
#include <bits/stdc++.h>
#include "books.h"
using namespace std;

#define Fi first
#define Se second
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
#define all(x) (x).begin(), (x).end()
#define pb push_back
#define szz(x) (int)(x).size()
#define rep(i, n) for(int i=0;i<(n);i++)
typedef tuple<int, int, int> t3;

int c[1000010], rrv[1000010], rv[1000010], T[1000010], S[1000010];
ll minimum_walk(vector<int> p, int s) {
	int n = szz(p);
	ll ans = 0;
	rep(i, n) {
		int l = i, r = p[i];
		if(l > r) swap(l, r);
		T[l]++, T[r]--;
		ans += r - l;
	}
	for(int i=1;i<n;i++) T[i] += T[i-1];
	rep(i, n) S[i] = (i ? S[i-1] : 0) + (T[i] == 0);
	auto gs = [&](int s, int e) {
		return (e ? S[e-1] : 0) - (s ? S[s-1] : 0);
	};
	rep(i, n) if(!c[i]) {
		int l = i, r = i;
		for(int j=p[i];j!=i;j=p[j]) l = min(l, j), r = max(r, j);
		c[i] = 1, rv[i] = r;
		for(int j=p[i];j!=i;j=p[j]) c[j] = 1, rv[j] = r;
	}
	rrv[0] = rv[0];
	for(int i=1;i<n;i++) rrv[i] = max(rv[i], rrv[i-1]);
	int l = s, r = s;
	vector <int> q; q.pb(s);
	auto push = [&](int x) {
		if(l > x) {
			for(int a=l-1;a>=x;a--) q.pb(a);
			l = x;
		}
		if(r < x) {
			for(int a=r+1;a<=x;a++) q.pb(a);
			r = x;
		}
	};
	while(1) {
		rep(i, szz(q)) {
			int t = q[i];
			if(c[t]) continue;
			c[t] = 1;
			for(int x=p[t];x!=t;x=p[x]) {
				push(x);
				c[x] = 1;
			}
		}
		if(l == 0 || rrv[l-1] <= r) break;
		q.clear();
		++ans;
		if(l) push(l-1);
		if(r < n-1) push(r+1);
	}
	int L = 0, R = n - 1;
	while(L < l && p[L] == L) ++L;
	while(r < R && p[R] == R) --R;
	ans += 2 * (gs(L, l) + gs(r, R));
	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...