首页 > 试题广场 >

火车进站

[编程题]火车进站
  • 热度指数:73449 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
给定一个正整数N代表火车数量,0<N<10,接下来输入火车入站的序列,一共N辆火车,每辆火车以数字1-9编号,火车站只有一个方向进出,同时停靠在火车站的列车中,只有后进站的出站了,先进站的才能出站
要求输出所有火车出站的方案,以字典序排序输出
数据范围:
进阶:时间复杂度:,空间复杂度:

输入描述:

第一行输入一个正整数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]这个序列是不可能实现的。     
from functools import cmp_to_key
import copy
def paix(x):
    if len(x) == 1:
        return [x]
    a_end = []
    zhan = []
    for i in range(0, len(x)):
        # 入栈部分都在zhan里
        zhan.append(x[i])
        # 对没入栈的那部分递归
        b = [j for j in x[i+1:]]
        a = paix(b)
        for j in range(len(a)):
            zhan1=copy.deepcopy(zhan)
            zhan1.reverse()
            a1=copy.deepcopy(a[j])
            a1 = a1 + zhan1
            a_end.append(a1)

        # 让入栈的部分出栈
        if i == len(x) - 1:
            zhan.reverse()
            a_end.append(zhan)
            continue

        a2 = paix(zhan)
        a_end2 = [i2 + j2 for i2 in a2 for j2 in a]
        a_end += a_end2
    # qucong
    b_end=[]
    for i in a_end:
        if i not in b_end:
            b_end.append(i)
    return b_end

def pan(x1,x2):
    for i in range(0,len(x1)):
        if x1[i]!=x2[i]:
            return x1[i]-x2[i]
   

n = int(input())
x = list(map(int, input().split()))
mmap = paix(x)
mmap.sort(key=cmp_to_key(pan))
for i in mmap:
    out=""
    for j in i:
        out=out+str(j)+" "
    print(out)
发表于 2023-08-23 18:11:14 回复(0)
def updateTrainExitSequence(train_outside,train_inside,all_exit_way,exit_way_arr):
    if(train_outside):
        enter_train = train_outside.pop(0)
        train_inside.append(enter_train)
        updateTrainExitSequence(train_outside,train_inside,all_exit_way,exit_way_arr)
        train_inside.pop()
        train_outside.insert(0,enter_train)
    if(train_inside):
        exit_train = train_inside.pop()
        exit_way_arr.append(exit_train + " ")
        updateTrainExitSequence(train_outside,train_inside,all_exit_way,exit_way_arr)
        exit_way_arr.pop()
        train_inside.append(exit_train)
    if(not train_outside and not train_inside):
        all_exit_way.append("".join(exit_way_arr))


train_num = int(input())
train_outside = input().split()
all_exit_way = []
updateTrainExitSequence(train_outside,[],all_exit_way,[])
all_exit_way.sort()
for exit_way in all_exit_way: print(exit_way)

发表于 2023-07-28 15:23:47 回复(0)
    该代码核心思想参考其它大神(并非自创),我这边大概写一下我理解的思路
    n, nums = input(), input().split()
    res = []
    def dfs(w, i, o):

        # 如果没有 待需要进栈的火车 和 需要出栈的火车,证明所有火车都已出栈
        # 需要将都已出栈的火车添加到res
        if not w and not i:
            res.append(' '.join(map(str, o)))

        # 如果有 待需要进栈的火车,那么则安排一辆火车进栈
        if w:
            dfs(w[1:], i + [w[0]], o)

        #如果有进栈的火车,那么可以安排火车出栈
        if i:
            dfs(w, i[:-1], o + [i[-1]])
    dfs(nums, [], [])

    #sorted 按照题目要求,字典序输出
    for i in sorted(res):
        print(i)
发表于 2023-05-05 22:44:31 回复(2)
n=input().strip()
in_order=input().strip().split(' ')
res=[]

def in_out(station,waiting,out_station):
    if waiting:
        in_out(station+[waiting[0]],waiting[1:],out_station)
    if station:
        in_out(station[:-1],waiting,out_station+[station[-1]])
    if not station and not waiting:
        res.append(out_station)

in_out([],in_order,[])
res.sort()
for i in res:
    print(*i)

发表于 2023-05-04 13:39:17 回复(0)
n=int(input())
x=list(map(str,input().split()))
rem=[]
def ways(x=[],s=[],o=[]):
    if x==[] and s==[]:
        rem.append(o)
    if x:
        ways(x[1:],s+list(x[0]),o)
    if s:
        ways(x,s[:-1],o+list(s[-1]))

ways(x)
rem=list(sorted(rem))
for i in rem:
    print(*i)

发表于 2023-03-10 01:11:44 回复(0)
n = input()
ss = input().split()
ss.reverse()
ou = []
def cel(s, i, o):
    if not s and not i:
        ou.append(o)     
        return 
    if s:
        on = o.copy()
        sn = s.copy()
        sn.pop()
        inew = i.copy()
        inew.append(s[-1])
        cel(sn, inew, on)
    if i:
        on = o.copy()
        sn = s.copy()
        inew = i.copy()
        inew.pop()
        on.append(i[-1])
        cel(sn, inew, on)

cel(ss, [], [])

ou.sort()
for i in ou:
    for j in i:
        print(j, end=' ')
    print('')

发表于 2023-03-06 14:45:16 回复(0)
#此题动态规划解题,等候入站的序列和出站的序列不为空都会有
对应的入站和出站,边界为两者都为空时,将此时用于装出站序列的out列表
加入到出站方案列表中。
def trail(wait,stack,out):
    if not wait and not stack:#边界
        l.append(' '.join(map(str,out)))
    else:
        if wait:#入站
            trail(wait[1:],stack+[wait[0]],out)
        if stack:#出站
            trail(wait,stack[:-1],out+[stack[-1]])


while True:
    try:
        l = []
        n = int(input())
        wait = list(map(int,input().split()))
        trail(wait,[],[])
        l = sorted(l)#排序
        for i in l:
            print(i)
    except:
        break




发表于 2023-02-27 13:20:26 回复(0)
1、只有一辆车,一种方式
2、多辆车,分成两部分思考:
①前面的部分先进出完毕,后面的部分再进出完毕,
②前面的部分先进,后面的部分进出完毕后前面的再按顺序出
3、去重
4、排序
n=int(input())
s=list(map(int,input().split(' ')))

def inout(l:list):
    myl=[]
    if len(l)==1:
        myl.append(l)
    else:
        for i in range(1,len(l)):
            l1=inout(l[:i])
            l2=inout(l[i:])
            tmp=l[:i][::-1]
            for i in l1:
                for j in l2:
                    k=i+j
                    if k in myl:
                        continue
                    else:
                        myl.append(k)
            for j in l2:
                k=j+tmp
                if k in myl:
                    continue
                else:
                    myl.append(k)
    return(myl)

out=inout(s)
out=sorted(out)
for i in out:
    i=list(map(str,i))
    print(' '.join(i))


发表于 2023-02-17 16:16:07 回复(0)
真太难了,我麻瓜看不懂,看了一个多小时才理清楚了逻辑,一开始实在不理解递归return返回到哪里,运行里面没有break,没有循环如何做到一遍又一遍append结果。我的理解是套娃里面再套小娃:每次运行到站内为0 和出站都套娃一遍函数,然后检测到站内为最后一个火车就开始return,直接return到上一次出站,接着入站,反反复复的,有种反复横跳的感觉,最后返回完所有函数结束。所以函数运行了一遍,但又运行了n遍。
小白答案都得看几十遍
while True:
    try:
        n = int(input())
        trains = input().strip().split(" ")
        res = []

        def rec_trains(cur_index, in_trains, out_trains):
            # 最后一个火车已经入站,此时只能出站
            print( cur_index,in_trains,out_trains,'/')
            
            if trains[-1] in in_trains:
                res.append(" ".join(out_trains + in_trains[::-1]))
                # print(res,cur_index)
                return
            # 没有火车入站,此时只能入站
            elif in_trains == []:
                rec_trains(cur_index + 1, in_trains + [trains[cur_index]], out_trains)
            else:
                # 出站,当前车站的最后一个火车出战
                rec_trains(cur_index, in_trains[:-1], out_trains + [in_trains[-1]])
                # print(cur_index)
                # 入站,当前的火车入站
                rec_trains(cur_index + 1, in_trains + [trains[cur_index]], out_trains)

        rec_trains(0, [], [])
        res.sort()
        print("\n".join(res))
    except:
        break

发表于 2023-01-29 03:23:27 回复(1)
n, a = int(input()), list(map(int, input().split()))
a.sort()#未进站
b = [] #已进站
c = [] #已出站
def enters(a,b,c):#进站
    b = b + [a[0]] #防止覆盖变量
    a = a[1:]
    states(a,b,c)
def exits(a,b,c):#出站
    c = c + [b[-1]]
    b = b[0:-1]
    states(a,b,c)
def states(a,b,c):
    if len(c) == n:
        for i in c:
            print(i, end=" ")
        print()
    elif len(b) == 0:
        enters(a,b,c)
    elif len(a) == 0:
        exits(a,b,c)
    else:
        exits(a,b,c)
        enters(a,b,c)
states(a,b,c)
发表于 2021-12-09 18:00:08 回复(1)

python DFS就是香

class Solution:
    def __init__(self):
        self.ans = []

    def dfs(self, wait, stack, leave):
        if len(wait) == 0 and len(stack) == 0:
            self.ans.append(leave)

        if len(wait) > 0:  # 从等待队列中 入栈
            self.dfs(wait[1:], stack + [wait[0]], leave[:])

        if len(stack) > 0:  # 出栈
            self.dfs(wait[:], stack[:-1], leave + [stack[-1]])
        return self.ans

# 处理一些输入输出
if __name__ == '__main__':
    while True:
        try:
            n = input()
            nums = list(map(int, input().split()))
            sol = Solution()
            ret = sol.dfs(nums, [], [])
            for line in sorted(ret):
                print(" ".join(map(str, line)))
        except:
            break
发表于 2021-09-08 10:54:06 回复(0)

问题信息

难度:
13条回答 37374浏览

热门推荐

通过挑战的用户

查看代码