先奉上最短路径模板,建议ctrlC+ctrlV,再自己动手敲熟练,在考场上就能信手捏来~
#模板-最短路径
graph={}
cost={}
parent={}
visited=[]
def most_cheap(cost):
most_cheap,most_cheap_node=float('inf'),None
for node in cost.keys():
costs=cost[node]
if costs
搞懂经典例题的每一行代码含义,自己模拟一遍整个思路,最笨的方法也是最高效的方法。
#最短路径-例题
graph={}
graph['start']={'A':6,'B':2}
graph['A']={'end':1}
graph['B']={'A':3,'end':5}
graph['end']={}
#graph={'start': {'A': 6, 'B': 2}, 'A': {'end': 1}, 'B': {'A': 3, 'end': 5}, 'end': {}}
cost={}
cost['A']=6
cost['B']=2
cost['end']=float('inf')
#cost={'A': 6, 'B': 2, 'end': inf}
parent={}
parent['A']='start'
parent['B']='start'
parent['end']=None
#parent={'A': 'start', 'B': 'start', 'end': None}
visited=[]
def most_cheap(cost):
most_cheap,most_cheap_node=float('inf'),None
for node in cost.keys():#A B end
costs=cost[node]#6 2 inf | 5 2 7
if costs
学了上面这么多代码,怎么检验自己掌握了多少?很简单,来道真题练练手吧!
#最短路径-路径
def lcm(a,b):
s=a*b
while b:
a,b=b,a%b
return s//a
graph={}
for i in range(1,2022):
graph[i]={}
if i<=2000:
for j in range(i+1,i+22):
graph[i][j]=lcm(i,j)
else:
for j in range(i+1,2022):
graph[i][j]=lcm(i,j)
graph[2021]={}
cost={}
for i in graph[1]:
cost[i]=graph[1][i]
for i in range(23,2022):
cost[i]=float("inf")
parent={}
for i in range(2,23):
parent[i]=1
for i in range(23,2022):
parent[i]=None
v=[]
def mc(cost):
mc,mcn=float("inf"),None
for node in cost.keys():
costs=cost[node]#
if costs
参考资料:
第十二届蓝桥杯试题E 最短路径 Python 狄克斯特拉解法 超详细_m0_62277756的博客-CSDN博客
2021年第十二届蓝桥杯省赛Python组(真题+解析+代码):路径
我写的是关于蓝桥杯的系列题解,感谢关注我的朋友们,我会持续输出高质量文章