给定一个正整数N代表火车数量,0<N<10,接下来输入火车入站的序列,一共N辆火车,每辆火车以数字1-9编号,火车站只有一个方向进出,同时停靠在火车站的列车中,只有后进站的出站了,先进站的才能出站。
要求输出所有火车出站的方案,以字典序排序输出。
#include<iostream>
#include<stack>
#include<algorithm>
using namespace std;
bool isOutNum(int *push,int *pop,int len)//判断pop是不是push的出栈序列
{
if(push==NULL || pop==NULL ||len<=0)
return false;
stack<int> Stack;
int i=0,j=0;
for(i=0;i<len;i++)//依次把push中的数入栈
{
Stack.push(push[i]);
while(j<len && Stack.size()!=0 && pop[j]==Stack.top())//依次判断pop序列每个值是否与栈顶相等
{
Stack.pop();
j++;
}
}
return Stack.empty();
}
int main()
{
int N;
while(cin>>N)
{
int *pushNum=new int [N];
int *popNum=new int [N];
for(int i=0;i<N;i++)
{
cin>>pushNum[i];
popNum[i]=pushNum[i];
}
sort(popNum,popNum+N);
do
{
if(isOutNum(pushNum,popNum,N))//如果该排列正确,则输出
{
for(int i=0;i<N-1;i++)
cout<<popNum[i]<<" ";
cout<<popNum[N-1]<<endl;
}
}
while(next_permutation(popNum,popNum+N));//获取下一个排列
}
return 0;
}
你题目的解答代码如下:
#include <iostream>
#include <string>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;
bool isOutNum(vector<int> push1,vector<int> pop1,int len){
if(push1.size()==0||pop1.size()==0){
return false;
}
stack<int> stk;
int j=0;
for(int i=0;i<len;i++){
stk.push(push1[i]);
while(j<len && stk.size()!=0 && pop1[j]==stk.top()){
stk.pop();
j++;
}
}
return stk.empty(); //全部弹出
}
int main()
{
int N;
while(cin>>N){
vector<int> pushnum(N);
vector<int> popnum(N);
popnum.clear();
for(int i=0;i<N;i++){
cin>>pushnum[i];
popnum.push_back(pushnum[i]);
}
sort(popnum.begin(),popnum.end());
do{
bool res=isOutNum(pushnum, popnum, N);
if(res){
for(int i=0;i<N;i++)
{
cout<<popnum[i]<<" ";
}
cout<<endl;
}
}while(next_permutation(popnum.begin(),popnum.end()));
}
return 0;
}
如有帮助,望采纳!谢谢!