HJ77 火车进站

描述

给定一个正整数N代表火车数量,0<N<10,接下来输入火车入站的序列,一共N辆火车,每辆火车以数字1-9编号,火车站只有一个方向进出,同时停靠在火车站的列车中,只有后进站的出站了,先进站的才能出站。

要求输出所有火车出站的方案,以字典序排序输出。

数据范围:1\le n\le 10\1≤n≤10 

进阶:时间复杂度:O(n!)\O(n!) ,空间复杂度:O(n)\O(n) 

输入描述:

第一行输入一个正整数N(0 < N <= 10),第二行包括N个正整数,范围为1到10。

输出描述:

输出以字典序从小到大排序的火车出站序列号,每个编号以空格隔开,每个输出序列换行,具体见sample。

示例1

输入:

3
1 2 3

复制输出:

1 2 3
1 3 2
2 1 3
2 3 1
3 2 1

复制说明:

第一种方案:1进、1出、2进、2出、3进、3出
第二种方案:1进、1出、2进、3进、3出、2出
第三种方案:1进、2进、2出、1出、3进、3出
第四种方案:1进、2进、2出、3进、3出、1出
第五种方案:1进、2进、3进、3出、2出、1出
请注意,[3,1,2]这个序列是不可能实现的。    
#include <bits/stdc++.h>

//判断入栈顺序和出栈顺序是否一致
int checkStack(std::vector<int> inVect, std::vector<int> temp)
{
    std::stack<int> _stack; 
    int j = 0;          //j是出栈的顺序 
    for(int i = 0; i < inVect.size(); ++i)
    {
        _stack.push(inVect[i]);
        while(j < temp.size() && _stack.size() != 0 && _stack.top() == temp[j])
        {
            _stack.pop();
            j++;
        }
    }

    return _stack.empty();
}

int main()
{
    int n;
    std::cin >> n;
    std::vector<int> inVect;
    while(n--)
    {
        int temp;
        std::cin >> temp;
        inVect.push_back(temp);
    }
    std::vector<int> temp = inVect;
    std::sort(temp.begin(), temp.end());
    do
    {
        if(checkStack(inVect, temp))
        {
            for(int i = 0;i < temp.size(); ++i)
            {
                std::cout << temp[i] << " ";
            }
            std::cout << std::endl;
        }
    } while (std::next_permutation(temp.begin(), temp.end()));
    
    return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值