[noip2008]双栈排序

#链接#

【问题描述】
Tom最近在研究一个有趣的排序问题。如图所示,通过2个栈S1和S2,Tom希望借助以下4种操作实现将输入序列升序排序。
操作a
如果输入序列不为空,将第一个元素压入栈S1
操作b
如果栈S1不为空,将S1栈顶元素弹出至输出序列
操作c
如果输入序列不为空,将第一个元素压入栈S2
操作d
如果栈S2不为空,将S2栈顶元素弹出至输出序列
如果一个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希望知道其中字典序最小的操作序列是什么。
【输入】
输入文件twostack.in的第一行是一个整数n。
第二行有n个用空格隔开的正整数,构成一个1~n的排列。
【输出】
输出文件twostack.out共一行,如果输入的排列不是“可双栈排序排列”,输出数字0;否则输出字典序最小的操作序列,每两个操作之间用空格隔开,行尾没有空格。
【输入输出样例1】
twostack.in twostack.out
4
1 3 2 4 a b a a b b a b
【输入输出样例2】
twostack.in twostack.out
4
2 3 4 1 0
【输入输出样例3】
twostack.in twostack.out
3
2 3 1 a c a b b d
【限制】
30%的数据满足: n<=10
50%的数据满足: n<=50
100%的数据满足: n<=1000

二分图染色
对于任意两个数q1[i]和q1[j]不能压入同一个栈中的充要条件p是:存在一个k,使得i < j < k 且 q1[k]<q1[i] < q1[j]

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<queue>
#include<stack>
#define ll long long
using namespace std;

const int maxn = 10000 + 100;
int n;
int a[maxn];
struct edge{
	int u,v;
	int next;
}e[maxn];
int head[maxn], tot = 0;
int mi[maxn];

void add(int u, int v) {
	e[++tot] = (edge){u,v,head[u]};
	head[u] = tot;
}

int read() {
    int x = 0, t = 1;
    char ch = getchar();
    while(ch < '0' || ch >'9'){
        if(ch == '-') t = -1;
        ch = getchar();
    }
    while(ch >= '0' && ch <= '9'){
        x = x * 10 + ch - '0';
        ch = getchar();
    }
    return x * t;
}

int col[maxn];

bool bfs(int x) {
	queue<int>q;
	q.push(x);
	col[x] = 1;
	while(!q.empty()) {
		int k = q.front();
		q.pop();
		for(int i = head[k]; i; i = e[i].next) {
			int v = e[i].v;
			if(!col[v]) {
				col[v] = 3 - col[k];
				q.push(v);
			}
			else if(col[v] == col[k]) return 0;
		}
	}
	return 1;
}

int main() {
	n = read();
	for(int i = 1; i <= n; i++) a[i] = read();
	mi[n] = a[n];
	for(int i = n-1; i >= 1; i--) mi[i] = min(mi[i+1],a[i]);
	for(int i = 1; i <= n; i++) {
		for(int j = i + 1; j <= n; j++) {
			if(a[i] < a[j] && a[i] > mi[j]) {
				add(i,j);
				add(j,i);
			}
		}
	}
	for(int i = 1; i <= n; i++){
		if(!col[i]) 
			if(!bfs(i)){
				cout<<0<<endl;
				return 0;
			}
	}
	stack<int>q1,q2;
	int cnt = 1;
	for(int i = 1; i <= n;i++) {
		if(col[i] == 1){
			q1.push(a[i]);
			cout<<"a ";
		} 
		else {
			q2.push(a[i]);
			cout<<"c ";
		}
		while((!q1.empty()&&q1.top() == cnt) || (!q2.empty()&&q2.top() == cnt)) {
			if(!q1.empty()&&q1.top() == cnt) {
				cout<<"b ";
				q1.pop();
			}
			else {
				cout<<"d ";
				q2.pop();
			}
			cnt++;
		}
	}
	return 0;	
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值