P1155
题意
给定一个由
算法
通过观察,我们可以发现,当
想到使用二分图匹配的方法求解:若存在上述三元组,意味着
接下来采用二分图染色法判定二分图,即寻找图中是否存在奇环,操作为 dfs 匹配。此步骤为二分图处理的经典算法,略。
若上述流程成功匹配二分图,则可根据染色结果直接得出出入栈的操作序列
至此,算法结束,输出结果即可。
代码
#include <iostream>
#include <vector>
#include <cstdlib>
#include <stack>
using namespace std;
const int Max = 1005;
int n, cnt, a[Max], color[Max], t = 1;
vector<int> g[Max];
stack<int> s1, s2;
char s[Max << 2];
void dfs(int x, int c) {
color[x] = c;
for (int i = 0; i < g[x].size(); i++) {
int y = g[x][i];
if (!color[y])
dfs(y, 3 - c);
else if (color[y] == color[x]) { // 存在奇环,无解
cout << 0 << endl;
exit(0);
}
}
}
int main() {
cin >> n;
for (int i = 1; i <= n; i++)
cin >> a[i];
for (int i = n - 1, x = a[n]; i > 1; i--) {
for (int j = 1; j < i; j++)
if (x < a[j] && a[j] < a[i]) { // 符合条件,加边
g[a[i]].push_back(a[j]);
g[a[j]].push_back(a[i]);
}
x = min(x, a[i]);
}
for (int i = 1; i <= n; i++) // 二分图染色
if (!color[a[i]])
dfs(a[i], 1);
for (int i = 1; i <= n; i++) { // 根据染色结果得到操作序列
if (color[a[i]] == 1) {
s1.push(a[i]);
s[++cnt] = 'a';
} else {
s2.push(a[i]);
s[++cnt] = 'c';
}
while (!s1.empty() && s1.top() == t || !s2.empty() && s2.top() == t)
if (!s1.empty() && s1.top() == t) {
s1.pop();
s[++cnt] = 'b';
t++;
} else {
s2.pop();
s[++cnt] = 'd';
t++;
}
}
for (int i = cnt - 1; i; i--) // 微调字典序
for (int j = i; j < cnt; j++)
if (s[j] == 'c' && s[j + 1] == 'b' || s[j] == 'd' && s[j + 1] == 'a')
swap(s[j], s[j + 1]);
else
break;
for (int i = 1; i <= cnt; i++)
cout << s[i] << ' ';
return 0;
}