Description
Takahashi loves sorting.
He has a permutation (
p1
,
p2
,…,
pN
) of the integers from
1
through
First, we will define high and low elements in the permutation, as follows. The i-th element in the permutation is high if the maximum element between the 1-st and i-th elements, inclusive, is the i-th element itself, and otherwise the i-th element is low.
Then, let
Lastly, rearrange the permutation into (
b1
,
b2
,…,
bN−k
,
a1
,
a2
,…,
ak
).
How many operations are necessary until the permutation is sorted?
Solution
AGC好难啊,最后还是看了题解做的。。
题解的意思大概是对于一个排列,先不考虑
1
这个数。当经过
只要一个
for (int i = n - 1; i; i--) {
if (T[i + 1] == 0) {
if (q[i] > q[i + 1]) {
T[i] = 1; f[i] = i + 1;
}
} else {
if (Check(q[f[i + 1]], q[i], q[i + 1])) {
T[i] = T[i + 1]; f[i] = f[i + 1];
} else {
T[i] = T[i + 1] + 1; f[i] = i + 1;
}
}
}
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
const int N = 202020;
inline char get(void) {
static char buf[100000], *S = buf, *T = buf;
if (S == T) {
T = (S = buf) + fread(buf, 1, 100000, stdin);
if (S == T) return EOF;
}
return *S++;
}
template<typename T>
inline void read(T &x) {
static char c; x = 0; int sgn = 0;
for (c = get(); c < '0' || c > '9'; c = get()) if (c == '-') sgn = 1;
for (; c >= '0' && c <= '9'; c = get()) x = x * 10 + c - '0';
if (sgn) x = -x;
}
int n;
int p[N], q[N];
int f[N], T[N];
inline bool Check(int a, int b, int c) {
return (a < b && b < c) || (b < c && c < a) || (c < a && a < b);
}
int main(void) {
freopen("1.in", "r", stdin);
read(n);
for (int i = 1; i <= n; i++) {
read(p[i]); q[p[i]] = i;
}
for (int i = n - 1; i; i--) {
if (T[i + 1] == 0) {
if (q[i] > q[i + 1]) {
T[i] = 1; f[i] = i + 1;
}
} else {
if (Check(q[f[i + 1]], q[i], q[i + 1])) {
T[i] = T[i + 1]; f[i] = f[i + 1];
} else {
T[i] = T[i + 1] + 1; f[i] = i + 1;
}
}
}
cout << T[1] << endl;
}