[daily question 1] preparing for the Blue Bridge Cup -- Python programming | Day14 | path | real problem code analysis

Posted by james_4k2 on Wed, 09 Mar 2022 00:37:37 +0100

πŸ’– About the author: Hello, I'm brother cheshen, cheshen at No. 18 Fuxue road πŸ₯‡
⚑ About - > Che Shen: the fastest time from the bedroom to the laboratory is 3 minutes, and the slowest time is 3.5 minutes (that half minute is actually waiting for the traffic light)
πŸ“ Personal homepage: Drivers only need cars and hands, and the pressure comes from the paper_ Cheshen, 18 Fuxue Road_ CSDN blog
πŸ₯‡ Official certification: high-quality creators in the field of artificial intelligence
πŸŽ‰ give the thumbs-up βž• comment βž• Collection = = form a habit (one button three times) πŸ˜‹

⚑ I hope you can give me more support πŸ€—~ Let's come on together 😁

Brush one question every day without saying much. First brush the questions for nearly two years. Now it's the real question in 2021. If you have one together, you can join us!!!

Let's brush the questions together and impact the national competition!!!

Scan code My home page Group QR code at the bottom left of the page.

Joining method: you can add me on the wechat business card below, and then pull you into the group. (remember the note code: I want to win the National Award)

Overview of the 12th Blue Bridge Cup in 2021

These are the questions in 2020. There are two types: result filling and program design. We brush one question every day. There is no problem in saving the game!

Path (topic)

(total score of this question: 10 points)

Official practice system: https://www.lanqiao.cn/problems/1460/learning/

- > [problem description]

- > [result description]

This is a question filled in with results. You just need to calculate the results and submit them. The result of this question is an integer. When submitting the answer, only fill in this integer. If you fill in the redundant content, you will not be able to score.


By reading the stem of the question, this question - medium difficulty: ⭐⭐⭐

Type of investigation: dynamic programming, Dijkstra

Knowledge points: least common multiple, gcd(), math


The shortest path can be solved by dijikstra (dijestra algorithm) and dynamic programming. But the dynamic programming method is more recommended, which is simpler and more convenient!!!

  • Dijkstra algorithm is a typical single source shortest path algorithm, which is used to calculate the shortest path from one node to all other nodes. The main feature is to take the starting point as the center and expand outward layer by layer until it reaches the end point. From the for loop, the time complexity is O (n^2).

Edsger Wybe Dijkstra (May 11, 1930 ~ August 6, 2002), born in Rotterdam, the Netherlands,
Computer scientist, graduated from Leiden University in the Netherlands, studied physics and mathematics in his early years, and then changed to computing. He won the Turing prize known as the Nobel Prize in Computer Science in 1972, and later won AFIPS in 1974
Harry Goode Memorial Award, 1989 ACM SIGCSE outstanding contribution award in computer science education and teaching, and 2002 ACM
PODC most influential paper award—— Selected from< Baidu Encyclopedia: ezger dikoscher>

The specific algorithm can see one 4-minute Video Explanation of Chongqing little sister in station B (greedy thinking), there is a better one Station B video Five minutes makes it easier to understand.

Open it directly below!!!


Python code implementation:
Method 1: (Dijkstra)

#Dixtra algorithm
#Dictionary cost,graph,parents
#1: Find the cheapest node (not visited), and update (cost,parent) if its neighbor cost is smaller
def lcm(a,b):
    while b:
    return int(s/a)
for i in range(1,2022):
    if i<=2020:
        for j in range(i+1,i+22):
        for j in range(i+1,2022):
found=[]#Searched nodes
costs[1]=0#The starting point w is the cheapest point and the price is 0
def find(dict):#Find the cheapest node
    for k,v in dict.items():
        if k not in found and v<cost:
    return node
while node:
        for i in friend.keys():
            if costs[i]>friend[i]+costs[node]:
    except:#If there are no neighbors, costs will report an error, indicating that the end point has been reached, and you can print it
end=parent[2021]#Backtracking search layers
while end!=1:
print(count) 		#The length of the path is 10266837, which is traced 97 times

Method 2 (dynamic programming):

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2022/3/8 15:34
# @Author: cheshen, 18 Fuxue Road
# @Email   : yurz_control@163.com
# @File    : DP.py

# Of course, you can also use your own library to calculate the least common multiple
import math 				#Import math library
#print(math.gcd(a,b)) 		#Using function to solve the maximum common divisor
#print(a*b/math.gcd(a,b)) 	#Use the above function to solve the least common multiple 

INF = 0x3f3f3f3ff3ff  # Define a larger value
N = 2025  # The number of points is always more
d = [INF for i in range(N)]  # The subscript i represents the minimum value from the ith point to the first point
d[1] = 0

def gcd(a, b):
    if b == 0:
        return a
        return gcd(b, a % b)

def lcm(a, b):
    return int(a * b / gcd(a, b))  # 3812 16922 13191 16438

for i in range(1, N):  # Traverse from the first point
    for j in range(i + 1, min(N, i + 22)):  # i. every time you update, the next 21 points will start to update and retain the minimum
        d[j] = min(d[j], lcm(i, j) + d[i])  # The distance from point 1 to point j is always taken as small

print(d[2021])          # 10266837

The final result is 10266837

Thus, we can quickly get the results, and the verification is completed!

Today is the 14th day of brushing, the difficulty is ordinary, welcome to join, become stronger together, self-discipline together, and go to the national competition together!!!

Today's topic is generally ha. If you have different solutions, you can leave a message below~

Previous question brushing route:

Question brushing routeDetail
Day-01House plate making
Day-02Looking for 2020
Day-03Running exercise
Day-04Serpentine filling number
Day-06Decorative beads
Day-07Achievement statistics
Day-08Word analysis
Day-09Digital triangle
Day-10Plane segmentation
Day-12straight line
Day-13Cargo placement

Official question brushing exercise system: http://lx.lanqiao.cn/

❀ Keep reading Paper, keep taking notes, keep learning, and keep brushing LeetCode ❀!!!
Insist on writing questions!!! Impact national competition
⚑To Be No.1

⚑⚑ Ha ha ha ha

⚑ Creation is not easy ⚑, Crossing energy ❀ Follow, collect and like ❀ Three is the best

ღ( Β΄ο½₯α΄—ο½₯` )


Topics: Python Dynamic Programming dijkstra