蓝桥杯-十二届E题路径

代码

def gbs(x, y): # 最大公倍数
    if x>y:
        i = 1
        while((x*i)<=x*y):
            if (x*i)%y==0:
                return x*i
            else:
                i += 1
    elif x<y:
        i = 1
        while((y*i)<=y*x):
            if (y*i)%x==0:
                return y*i
            else:
                i += 1
    else:
        return x

# 建图
maxx = 500000000
gra = [[0]*2021 for i in range(2021)]
for i in range(2021):
    for j in range(2021):
        if i==j:
            weight = maxx
        elif abs(i-j)>21:
            weight = maxx
        elif abs(i-j)<=21:
            weight = gbs(i+1,j+1)
        gra[i][j] = weight

# 求最短路初始化
dist = list(0 for i in range(2021))
path = list(0 for i in range(2021))
s = list(0 for i in range(2021))
for j in range(2021):
    s[j] = 0
    dist[j] = gra[0][j]
    if gra[0][j]==maxx:
        path[j] = -1
    else:
        path[j] = 0

# 求最短路
s[0] = 1
path[0] = 0
dist[0] = 0
while(0 in s):
    minn = maxx
    for i in range(len(dist)):
        if s[i]==0 and dist[i]<minn:
            minn = dist[i]
            j = i
    s[j] = 1
    for k in range(len(dist)):
        if s[k]==0:
            if dist[k]>dist[j]+ gra[j][k]:
                dist[k] = dist[j]+ gra[j][k]
                path[k] = j

print(dist[2020])

代码

  • 建立二维数组aList = [[0] * cols for i in range(rows)]
  • 建立一维数组s = list(0 for i in range(nums))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值