双栈排序
题目背景:
分析: 考虑什么时候两个数a[i], a[j]不能进入同一个栈,当且仅当存在一个k,满足i < j < k 且 a[k] < a[i] < a[j],直接针对每一对i, j判断显然是n3的,我们可以先O(n)预处理一个数组max[i] 表示从第i位起,到第n位中最大的数是多少,然后就可以n2求得哪些不能进同一个栈,考虑如何判断,我们很容易想到二分图染色,将不能放在同一个栈的连边,二分图染色判定,是否合法即可,最后的方案输出直接模拟线第一个栈的操作再第二个即可。
Source:
/*
created by scarlyw
*/
#include <cstdio>
#include <string>
#include <algorithm>
#include <cstring>
#include <iostream>
#include <cmath>
#include <cctype>
#include <vector>
#include <set>
#include <queue>
inline char read() {
static const int IN_LEN = 1024 * 1024;
static char buf[IN_LEN], *s, *t;
if (s == t) {
t = (s = buf) + fread(buf, 1, IN_LEN, stdin);
if (s == t) return -1;
}
return *s++;
}
///*
template<class T>
inline void R(T &x) {
static char c;
static bool iosig;
for (c = read(), iosig = false; !isdigit(c); c = read()) {
if (c == -1) return ;
if (c == '-') iosig = true;
}
for (x = 0; isdigit(c); c = read())
x = ((x << 2) + x << 1) + (c ^ '0');
if (iosig) x = -x;
}
//*/
const int OUT_LEN = 1024 * 1024;
char obuf[OUT_LEN], *oh = obuf;
inline void write_char(char c) {
if (oh == obuf + OUT_LEN) fwrite(obuf, 1, OUT_LEN, stdout), oh = obuf;
*oh++ = c;
}
template<class T>
inline void W(T x) {
static int buf[30], cnt;
if (x == 0) write_char('0');
else {
if (x < 0) write_char('-'), x = -x;
for (cnt = 0; x; x /= 10) buf[++cnt] = x % 10 + 48;
while (cnt) write_char(buf[cnt--]);
}
}
inline void flush() {
fwrite(obuf, 1, oh - obuf, stdout);
}
/*
template<class T>
inline void R(T &x) {
static char c;
static bool iosig;
for (c = getchar(), iosig = false; !isdigit(c); c = getchar())
if (c == '-') iosig = true;
for (x = 0; isdigit(c); c = getchar())
x = ((x << 2) + x << 1) + (c ^ '0');
if (iosig) x = -x;
}
//*/
const int MAXN = 1000 + 10;
int n;
int min[MAXN], a[MAXN], color[MAXN];
std::vector<int> edge[MAXN], s1, s2;
inline void add_edge(int x, int y) {
edge[x].push_back(y), edge[y].push_back(x);
}
inline bool dfs(int cur, int c) {
color[cur] = c;
for (int p = 0; p < edge[cur].size(); ++p) {
int v = edge[cur][p];
if (color[v] == -c) continue ;
else if (color[v] == c) return false;
else if(dfs(v, -c) == false) return false;
}
return true;
}
int main() {
R(n), min[n + 1] = ~0u >> 1;
for (int i = 1; i <= n; ++i) R(a[i]);
for (int i = n; i >= 1; --i) min[i] = std::min(a[i], min[i + 1]);
for (int i = 1; i <= n; ++i)
for (int j = i + 1; j <= n; ++j)
if (a[i] < a[j] && min[j + 1] < a[i]) add_edge(i, j);
for (int i = 1; i <= n; ++i)
if (color[i] == 0) if (!dfs(i, 1)) std::cout << "0", exit(0);
int x = 1;
for (int i = 1; i <= n; ++i) {
if (color[i] == 1) s1.push_back(a[i]), write_char('a'), write_char(' ');
else s2.push_back(a[i]), write_char('c'), write_char(' ');
while ((!s1.empty() && s1.back() == x) ||
(!s2.empty() && s2.back() == x)) {
if (!s1.empty() && s1.back() == x)
write_char('b'), write_char(' '), s1.pop_back(), ++x;
else write_char('d'), write_char(' '), s2.pop_back(), ++x;
}
}
flush();
return 0;
}