描述 | |
---|---|
知识点 | 栈 |
运行时间限制 | 0M |
内存限制 | 0 |
输入 | 有多组测试用例,每一组第一行输入一个正整数N(0<N<10),第二行包括N个正整数,范围为1到9。 |
输出 | 输出以字典序排序的火车出站序列号,每个编号以空格隔开,每个输出序列换行,具体见sample。 |
样例输入 | 3 1 2 3 |
样例输出 | 1 2 3 1 3 2 2 1 3 2 3 1 3 2 1 |
#include <iostream>
#include <vector>
#include <string>
#include <deque>
#include <stack>
#include <map>
#include <algorithm>
using namespace std;
//算法步骤:
//(1)输入数组进行字典排序;
//(2)判断字典排序数组是否符合进出栈要求。
//函数名:isLexicographicalOrder
//输入:原始输入数组origin,字典排序数组vec
//输出:满足进出栈要求,返回true,否则,返回false
bool isLexicographicalOrder(vector<int> &origin,vector<int> vec)
{
stack<int> sta;
deque<int> deq;//双端队列deq存储字典排序数组
for (int i = 0; i < vec.size(); i++)
deq.push_back(vec[i]);
int index = 0;
while (!deq.empty())
{
if (index == origin.size())//如果条件满足,说明所有origin数组中的所有数据都已入栈,跳出
break;
while ((index < origin.size()) &&(sta.empty() || sta.top() != deq.front()))//模拟数据入栈
{
sta.push(origin[index]);
index++;
}
while (!sta.empty() && sta.top() == deq.front())//模拟数据出栈
{
sta.pop();
deq.pop_front();
}
}
if (deq.empty())
return true;
else
return false;
}
void main()
{
int N;
vector<int> vec;
vector<int> origin;
cin >> N;
for (int i = 0; i < N; i++)
{
int tmp;
cin >> tmp;
vec.push_back(tmp);
origin.push_back(tmp);
}
sort(vec.begin(), vec.end());
do
{
if (isLexicographicalOrder(origin, vec))
{
for (int i = 0; i < vec.size()-1; i++)
cout << vec[i] << " ";
cout << vec[vec.size()-1] << endl;
}
} while (next_permutation(vec.begin(), vec.end()));
}