Description
给一个排列
pn
,每次可以选择排列
p
中的相邻的两个数,把这两个数放到
要求最小化字典序
Solution
这不就是贪心啊。。
跟超级钢琴一样的做法。
因为这两个数在原排列中的奇偶性不同,开两颗线段树(好吧,是不想打ST表)存一下最小值的位置就好了。。
#include <bits/stdc++.h>
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 a[N];
int n, l, r;
struct Seg {
int c[N];
int mn[N << 2];
inline int MinPos(int a, int b) {
return c[a] < c[b] ? a : b;
}
inline void Build(int o, int l, int r) {
if (l == r) return (void)(mn[o] = l);
int mid = (l + r) >> 1;
Build(o << 1, l, mid);
Build(o << 1 | 1, mid + 1, r);
mn[o] = MinPos(mn[o << 1], mn[o << 1 | 1]);
}
inline void Init(int fl) {
for (int i = 0; i <= n; i++) c[i] = N;
for (int i = fl; i <= n; i += 2)
c[i] = a[i];
Build(1, 1, n);
}
inline int MinPos(int o, int l, int r, int L, int R) {
if (l >= L && r <= R) return mn[o];
int mid = (l + r) >> 1, res = 0;
if (L <= mid) res = MinPos(res, MinPos(o << 1, l, mid, L, R));
if (R > mid) res = MinPos(res, MinPos(o << 1 | 1, mid + 1, r, L, R));
return res;
}
};
Seg S[2];
struct cpp {
int l, r, s, t, fl;
cpp(void) {}
cpp(int _l, int _r, int f) {
l = _l; r = _r; fl = f;
s = S[fl].MinPos(1, 1, n, l, r);
t = S[fl ^ 1].MinPos(1, 1, n, s, r);
}
inline bool operator <(const cpp &x) const{
return a[s] > a[x.s];
}
};
cpp x;
priority_queue<cpp> Q;
int main(void) {
read(n);
for (int i = 1; i <= n; i++) read(a[i]);
S[1].Init(1); S[0].Init(2);
Q.push(cpp(1, n, 1));
while (!Q.empty()) {
x = Q.top(); Q.pop();
printf("%d %d ", a[x.s], a[x.t]);
if (x.l < x.s) Q.push(cpp(x.l, x.s - 1, x.fl));
if (x.t < x.r) Q.push(cpp(x.t + 1, x.r, x.fl));
if (x.s + 1 < x.t) Q.push(cpp(x.s + 1, x.t - 1, x.fl ^ 1));
}
return 0;
}