题解 | #火车进站#
火车进站
http://www.nowcoder.com/practice/97ba57c35e9f4749826dc3befaeae109
利用“进出”操作的排列
while True:
try:
n = int(input())
trains = input().split()
perm = [[] for _ in range(n+1)]
perm[1] = ['ab']
for i in range(2, n+1):
for x in perm[i-1]:
for j in range(len(x)):
sub = list(x)
sub.insert(j, 'a')
sub.insert(j+1, 'b')
sub = ''.join(sub)
if not sub in perm[i]:
perm[i].append(sub)
res = []
for pe in perm[n]:
stack = []
t = 0
out = ''
for c in pe:
if c == 'a':
stack.append(trains[t])
t += 1
else:
out += stack.pop()
res.append(out)
res.sort()
res = [' '.join(list(r)) for r in res]
for r in res:
print(r)
except:
break