Tom最近在研究一个有趣的排序问题。如图所示,通过2个栈S1和S2,Tom希望借助以下4种操作实现将输入序列升序排序。
[IMG]http://www.tyvj.cn:8080/ProblemImg/1121-1.gif[/IMG]
操作a
如果输入序列不为空,将第一个元素压入栈S1
操作b
如果栈S1不为空,将S1栈顶元素弹出至输出序列
操作c
如果输入序列不为空,将第一个元素压入栈S2
操作d
如果栈S2不为空,将S2栈顶元素弹出至输出序列
[IMG]http://www.tyvj.cn:8080/ProblemImg/1121-2.gif[/IMG]
如果一个1~n的排列P可以通过一系列操作使得输出序列为1, 2,…,(n-1), n,Tom就称P是一个"可双栈排序排列"。例如(1, 3, 2, 4)就是一个"可双栈排序序列",而(2, 3, 4, 1)不是。下图描述了一个将(1, 3, 2, 4)排序的操作序列:<a, c, c, b, a, d, d, b>
当然,这样的操作序列有可能有几个,对于上例(1, 3, 2, 4),<a, c, c, b, a, d, d, b>是另外一个可行的操作序列。Tom希望知道其中字典序最小的操作序列是什么。
思路:
题目上说的105的,结果标准代码是O(n2)的,我人傻了
对于数组里面的三个数i<j<k,如果aj>ai&&ak<ai,比如说2 3 1,那么一个栈肯定是不能解决问题的,所以要用两个栈,然后染色一下就行了。
就是一个二分图的问题,
#include <cstdio>
#include <iostream>
#include <iomanip>
#include <string>
#include <cstdlib>
#include <cstring>
#include <queue>
#include <set>
#include <vector>
#include <map>
#include <algorithm>
#include <cmath>
#include <stack>
#define INF 0x3f3f3f3f
#define IMAX 2147483646
#define LINF 0x3f3f3f3f3f3f3f3f
#define ll long long
#define ull unsigned long long
#define uint unsigned int
using namespace std;
int n, a[1111],t, f[1111], color[1111];
bool g[1111][1111];
bool dfs(int u, int c) {
color[u] = c;
for(int i = 1;i<=n;i++)
if (g[u][i]) {
if (color[i] == c) return false;
if (color[i] < 0 && !dfs(i, !c))return false;
}
return true;
}
int main() {
memset(color, -1, sizeof(color));
cout << color[0];
scanf("%d", &t);
while(t--){
scanf("%d", &n);
for (int i = 1; i <= n; i++)
scanf("%d", a + i);
f[n + 1] = n + 1;
memset(g, 0, sizeof(g));
for (int i = n; i; i--)f[i] = min(f[i + 1], a[i]);
for (int i = 1; i <= n; i++)
for (int j = i + 1; j <= n; j++)//2 3 1;i和j逆序且j后面有更大的,所以i和j不能在二分图的同一个部分
if (a[i] < a[j] && f[j + 1] < a[i])
g[i][j] = g[j][i] = 1;
memset(color, -1, sizeof(color));
bool flag = 1;
for(int i = 1;i<=n;i++)
if (color[i] < 0 && !dfs(i, 0)) {
flag = 0;
break;
}
if (!flag) {
printf("0\n");
continue;
}
stack<int> stk1, stk2;
int now = 1;
for (int i = 1; i <= n; i++){
if (color[i] == 0){
while (stk1.size() && stk1.top() == now){
stk1.pop();
printf("b ");
now++;
}
stk1.push(a[i]);
printf("a ");
}
else{
while (true)
if (stk1.size() && stk1.top() == now){
stk1.pop();
printf("b ");
now++;
}
else if (stk2.size() && stk2.top() == now){
stk2.pop();
printf("d ");
now++;
}
else break;
stk2.push(a[i]);
printf("c ");
}
}
while (true)
if (stk1.size() && stk1.top() == now){
stk1.pop();
printf("b ");
now++;
}
else if (stk2.size() && stk2.top() == now){
stk2.pop();
printf("d ");
now++;
}
else break;
cout << endl;
}
return 0;
}