1 算法模板
先奉上最短路径模板,建议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<most_cheap and node not in visited:
most_cheap,most_cheap_node=costs,node
return most_cheap_node
node=most_cheap(cost)
while node:
costs=cost[node]
neighbor=graph[node]
for i in neighbor.keys():
new_cost=costs+neighbor[i]
if new_cost<cost[i]:
cost[i]=new_cost
parent[i]=node
visited.append(node)
node=most_cheap(cost)
2 经典例题
搞懂经典例题的每一行代码含义,自己模拟一遍整个思路,最笨的方法也是最高效的方法。
#最短路径-例题
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<most_cheap and node not in visited:
most_cheap,most_cheap_node=costs,node
return most_cheap_node #B | A
node=most_cheap(cost)#从未处理过的节点中找出最便宜的节点
while node:#只要还有未处理的节点就执行#node:B |A
costs=cost[node]#起点到该节点的最短开销#costs=2 |5
neighbor=graph[node]#传入邻居以及当前节点到邻居的开销#neighbor={'A': 3, 'end': 5}|{'end': 1}
for i in neighbor.keys():#遍历所有邻居 i:A end |end
new_cost=costs+neighbor[i]#新开销 2+3=5 2+5=7 |5+1=6
#cost={'A': 6, 'B': 2, 'end': inf} |{'A': 5, 'B': 2, 'end': 7}
if new_cost<cost[i]:#5<6 7<inf |6<7
cost[i]=new_cost#更新开销 5 7 |6
parent[i]=node#更新父节点 B B |A
#cost={'A': 5, 'B': 2, 'end': 7} |{'A': 5, 'B': 2, 'end': 6}
visited.append(node)#记录处理过的节点 B
node=most_cheap(cost)#循环执行
print(cost)#{'A': 5, 'B': 2, 'end': 6}
3 实战题目
学了上面这么多代码,怎么检验自己掌握了多少?很简单,来道真题练练手吧!
#最短路径-路径
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<mc and node not in v:
mc,mcn=costs,node
return mcn
node=mc(cost)
while node:
costs=cost[node]
nb=graph[node]
for i in nb.keys():
new=costs+nb[i]
if new<cost[i]:
cost[i]=new
parent[i]=node
v.append(node)
node=mc(cost)
print(cost[2021])#10266837
参考资料:
第十二届蓝桥杯试题E 最短路径 Python 狄克斯特拉解法 超详细_m0_62277756的博客-CSDN博客
2021年第十二届蓝桥杯省赛Python组(真题+解析+代码):路径
📍我写的是关于蓝桥杯的系列题解,感谢关注我的朋友们,我会持续输出高质量文章💪🏻