题目描述
给定一个正整数N代表火车数量,0<N<10,接下来输入火车入站的序列,一共N辆火车,每辆火车以数字1-9编号。要求以字典序排序输出火车出站的序列号。
输入描述:
有多组测试用例,每一组第一行输入一个正整数N(0<N<10),第二行包括N个正整数,范围为1到9。
输出描述:
输出以字典序从小到大排序的火车出站序列号,每个编号以空格隔开,每个输出序列换行,具体见sample。
示例1
输入
复制
3
1 2 3
输出
复制
1 2 3
1 3 2
2 1 3
2 3 1
3 2 1
#include
#include
#include
#include
using namespace std;
bool isOutNum(vector&push, vector&pop, int n)
{
if(n<=0)
return false;
stack<int> s;
int i = 0, j =0;
for(; i < n ;i++)
{
s.push(push[i]);
while(j<n && s.size()!=0 && pop[j]==s.top())
{
s.pop();
j++;
}
}
return s.empty();
}
int main()
{
int n;
while (cin >> n)
{
vector push(n);
vector pop(n);
for (int i = 0; i < n; i++)
{
cin >> push[i];
pop[i] = push[i];
}
sort(pop.begin(), pop.end());
do
{
if (isOutNum(push, pop, n))
{
for (int i = 0; i < n; i++)
{
cout << pop[i] << " ";
}
cout << endl;
}
} while (next_permutation(pop.begin(), pop.end()));
}
return 0;
}