Problem 抓住薛定谔的猫
问题描述:
思路1(注意:失败!):根据x与y之间的距离来决定步数,使得|y-x|最小。
代码如下:
def choose(x,y):
d = {-1:abs(y-(x-1)),1:abs(y-(x+1)),10:abs(y-(x+10)),2:abs(y-(x*2))}
#每次返回距离y更近的选择
return min(d,key=d.get)
x , y = list(map(int,input().split()))
time = 0 #所花时间
while x != y:
if choose(x,y) == 2:
x*=2
else:
x+=choose(x,y)
time+=1
print(time)
输出如下:
错误原因:每次寻找最快逼近y的步长会错失掉很多可能性,所以也反映了一个哲学问题 the fast does not always represent the best,漫漫人生路还是得有快有慢才行。
改进思路:从第一个数字开始 他可以产生四个结果,然后再每一个结果又产生四个结果,直到找到等于y的就结束** (像树一样)
代码如下:
#每次对Lisy中的元素做四个选择操作,返回列表至nums[-1]
def operate(List,digit):
results = []
for i in List:
if i-1 >-1 and i-1 <110000 and digit[i-1] == 0 :
results.append(i-1)
digit[i-1] = 1
if i+1 >-1 and i+1 <110000 and digit[i+1] == 0 :
results.append(i+1)
digit[i+1] = 1
if i+10 >-1 and i-1 <110000 and digit[i+10] == 0 :
results.append(i+10)
digit[i+10] = 1
if i*2 >-1 and i*2 <110000 and digit[i*2] == 0 :
results.append(i*2)
digit[i*2] = 1
return results
x , y = list(map(int,input().split()))
nums = []
digit = [0 for i in range(110000)] #未避免数量级过大,而越过已经访问过的数字
nums.append(operate([x],digit))
time = 1
while y not in nums[-1]:
nums.append(operate(nums[-1],digit))
time+=1
print(time)
输出结果: