Python,176个字节
n=int(1e8);s,f,L=0,input(),[1,0]+[n]*(n-1)
def h(q):
if 0<=q<=n and L[q]>s:L[q]=s+1
while n in L:
for i,v in enumerate(L):
if v==s:map(h,(i-1,i+1,i*2,i*3))
s+=1
print L[f]
一路蛮力;1 to 100,000,00064位计算机上的所有数字列表约为800Mb的内存。
列表索引代表数字,值代表在允许的救援步骤中距1的距离。
- 设置列表[1] = 0表示“可在0步内到达”。
- 对于列表中每个数字(可通过0步访问
1)(即)
- 一步即可到达列表中的每个数字(即
0,2,2,3)
- 设置编号+1,编号-1,编号* 2,编号* 3可分两步访问
- ...等等,直到达到每个列表索引。
运行时间超过10分钟。*天哪*。
代码注释
n=int(1e8) # max input limit.
s=0 # tracks moves from 1 to a given number.
f=input() # user input.
L=[1,0]+[n]*(n-1) # A list where 0 can get to room 1 in 1 step,
# 1 can get to itself in 0 steps,
# all other rooms can get to room 1 in
# max-input-limit steps as a huge upper bound.
def helper(q):
if 0<=q<=n: # Don't exceed the list boundaries.
if L[q]>s: # If we've already got to this room in fewer steps
# don't update it with a longer path.
L[q]=s+1 # Can get between rooms 1 and q in steps+1 actions.
while n in L: # until there are no values still at the
# original huge upper bound
for i,v in enumerate(L):
if v==s: # only pick out list items
# rechable in current s steps,
map(helper,(i-1,i+1,i*2,i*3)) # and set the next ones reachable
# in s+1 steps.
s+=1 # Go through the list again to find
# rooms reachable in s+1 steps
print L[f] # show answer to the user.
其他
- 如果在PythonWin中运行它,则可以随后在解释器中访问列表L。
- 每个房间都有30步或更少的步长到达船长的路径。
- 只有一个房间离开30个房间-72,559,411房间-共有244个房间离开29个房间。
- 对于大多数情况,它可能具有可怕的运行时特性,但是问题注释之一是“ @Geobits将在5分钟内为20000个测试用例找到最短方法的所有程序 ”,并在<6秒内测试1-20,001。