题目链接
https://www.acwing.com/problem/content/131/
这里有n列火车将要进站再出站,但是,每列火车只有1节,那就是车头。
这n列火车按1到n的顺序从东方左转进站,这个车站是南北方向的,它虽然无限长,只可惜是一个死胡同,而且站台只有一条股道,火车只能倒着从西方出去,而且每列火车必须进站,先进后出。
也就是说这个火车站其实就相当于一个栈,每次可以让右侧头火车进栈,或者让栈顶火车出站。
车站示意如图:
出站<—— <——进站
|车|
|站|
|__|
现在请你按《字典序》输出前20种可能的出栈方案。
输入格式
输入一个整数n,代表火车数量。
输出格式
按照《字典序》输出前20种答案,每行一种,不要空格。
数据范围
1≤n≤20
输入样例:
3
输出样例:
123
132
213
231
321
题解
每次操作有两种,操作1是外边的一辆车进站,操作2是站里的车出去一辆。
然后每次在既可以选择操作1,又可以选择操作2的情况下,优先选择操作2,因为这样得到的出队序列字典序小。
还有一道题是算出栈序列有多少种结果,这个问题我在另一个博客写了。
https://blog.csdn.net/weixin_42757232/article/details/89044444
代码
#include<iostream>
#include<cstring>
#include<cstdio>
#include<vector>
#include<stack>
#include<algorithm>
using namespace std;
typedef long long ll;
int n;
stack<int> state2;
int state1=1;
vector<int> state3;
int cnt=20;
void dfs(){
if(!cnt) return;
if(state3.size()==n){
cnt--;
for(int i=0;i<n;i++){
cout<<state3[i];
}
cout<<endl;
return ;
}
if(state2.size()){
state3.push_back(state2.top());
state2.pop();
dfs();
state2.push(state3.back());
state3.pop_back();
}
if(state1<=n){
state2.push(state1);
state1++;
dfs();
state1--;
state2.pop();
}
}
int main(){
cin>>n;
dfs();
return 0;
}