火车进站问题

来源:互联网 发布:如何建立阿里云服务器 编辑:程序博客网 时间:2024/04/29 10:12

给定一个正整数N代表火车数量,0<N<10,接下来输入火车入站的序列,一共N辆火车,每辆火车以数字1-9编号。要求以字典序排序输出火车出站的序列号。

比如火车进站 序列问题:

C++代码:

#include <iostream>

#include<stdio.h>
#include<stack>
#include <vector>


using std::stack;
using std::vector;
using namespace std;
bool IspopOrder(const int* put_order,const int* pop_order,int length ) //判断一个序列是不是输入的序列的出站序列
{
bool possible=false;
if(put_order!=NULL&&pop_order!=NULL&&length>0)
{
const int* next_put=put_order;
const int* next_pop=pop_order;
std::stack<int> stackdata;
while(next_pop-pop_order<length)
{
while(stackdata.empty()||stackdata.top()!=*next_pop)
{
if(next_put-put_order==length)
break;
stackdata.push(*next_put);
next_put++;
}


if(stackdata.top()!=*next_pop)
break;
stackdata.pop();
++next_pop;
}
if(stackdata.empty()&&next_pop-pop_order==length)
possible=true;
}
return possible;
}


void Problem_Train_Core(int* Original_sequence,int* pbegin,int length,int Index)  //输出所有出站序列
{
if(Index==length)
{
if(IspopOrder(Original_sequence,pbegin,length))
{
for(int i=0;i<length;i++)
{
printf("%d ",pbegin[i]);
}
printf("\n");
}
}
else
{
for(int i=Index;i<length;i++)

int temp=pbegin[Index];
pbegin[Index]=pbegin[i];
pbegin[i]=temp;
Problem_Train_Core(Original_sequence,pbegin,length, Index+1);
temp=pbegin[Index];
pbegin[Index]=pbegin[i];
pbegin[i]=temp;
}
}
}
void Problem_Train(int* train_sequence,int length)

 {
if(length<0) 
return;
int Original_sequence[50];
for(int i=0;i<length;i++)
{
Original_sequence[i]=train_sequence[i];
}


Problem_Train_Core(Original_sequence,train_sequence,length,0);
 }


int main()
{    int sequence[4]={1,2,3,4};
Problem_Train(sequence,3);
return 0;
}
0 0
原创粉丝点击