[Summary of PYthon the day before the Blue Bridge Cup exam]

The shortest path to Floyd:

Applicable field: It can be either directed graph or undirected graph, the weight can be negative, usually used to find the distance between vertices (multi-source)

The disadvantage is that the time complexity is high, and Python itself runs slowly.... I pray that the amount of data in this question is not too large

The advantage is that compared to Dijkstra's algorithm, it is simpler, less code, and easier to use.

board:

n=int(input())#这个根据题意设置,表示结点个数

edge=[[float('inf')]*n for i in range(n)]
#初始化所有边权为无穷大


#根据题意更新edge[i][j]
#更新的时候,如果有无向图需要edge[i][j]=edge[j][i]这样设置,否则不用


#三重循环 结束
for k in range(n):
    for i in range(n):
        for j in range(n):
            edge[i][j]=min(edge[i][j],edge[i][k]+edge[k][j])


Dijkstra's Shortest Path:

Applicable field: It can be either an undirected graph or a directed graph. The weight must be non-negative. Find the shortest distance from a vertex to other vertices (single source)

Disadvantages: It will be a little more troublesome to write. There are more things than Floyd.

Advantages: It runs very fast, and it can be solved with Python when the amount of data is relatively large

board:


n=int(input())#根据题意 n代表结点个数

edge={}
#edge[i]={x:费用1,y:费用1....} 存结点之间的费用

cost=[]
#cost[i]代表结点i到出发点的最短开销

s=set()
#集合s用于存储处理过的结点

def find_node():#find_node函数用于寻找未被处理过的最便宜的结点
    node,spend=None,float('inf')
    for i in range(n):
        if cost[i]<=spend and i not in s:#
            node,spend=i,cost[i]
    return node

while node:#只要还有结点未被处理
    for i in edge[node]:#遍历node的邻居
        cost[i]=min(cost[i],cost[node]+edge[node][i])
    s.add(node)
    node=find_node



print(#根据你的需要输出出发点到某个结点i的费用cost[i])

    
#此外补充一个,如果题还要我们求最短路径上边的个数
#只需外加一个字典pre 每当更新cost[i]时,创建一个键值对
#最后通过终点逆向遍历统计次数即边数 输出即可

Modulo algorithm:

Knowledge point: if x>y>0, if p=x%y, then p must be less than y, that is, p∈[0,y-1] 

Two consecutive visits to this knowledge point! ! Pay attention to

Two-point answer, Bisect module:

In the question, there is the minimum value of the largest so-and-so, and the maximum value of the smallest so-and-so. When there is no idea, you can often directly go to the two-point answer.

Board: check function is the core

#l,r根据题意设置 红蓝区域自己定义划分


def check(x):
    #假设x为答案
    #题目一般有有个约束条件
    #如果通过某种手段使得在x的条件下存在符合约束条件的解
    #那么就是可行解



while l+1!=r:
    mid=(l+r)//2
    if check(mid):
        r=mid
    else:
        l=mid


#取l还是r依据需要

Bisect module: (can only be used in ascending arrays, it is defaulted to QWQ when its source code is written)

import bisect

a=[0,1,2,3,3,3,5]#一段升序数组

bisect.bisect(a,b)

#返回数组a中最后一个<=b的数字的下标+1

#bisect.bisect(a,3)返回6

bisect.bisect_left(a,3)

#返回数组中第一个等于3的下标

#bisect.bisect_left(a,3)返回3

#如果不存在等于3的,和bisect.bisect等效

bisect.bisect_right(a,3)

#返回数组中最后一个等于3的下标+1

#bisect.bisect_right(a,3)返回6

#如果不存在等于3的,和bisect.bisect等效


This module is usually used to query the number of numbers belonging to a certain interval in a sequence, >=p or <=p? It is very efficient

Of course, you can also directly use the list comprehension +len function, but the efficiency is not high

len([i for i in a if i<=p])
#p自己设定

[Contribution value method] : To study the increment of the result after a single element is introduced , it is actually to transform a complex big problem into a small problem. When the problem is difficult to start, you can consider this method

And check the set:

board


n=int(input())
#根据题意输入节点个数
#初始化
parent=[i for i in range(n)]



#查找
def find_root(x):
    if parent[x]!=x:
        parent[x]=find_root(parent[x])
    return parent[x]
#合并
def uion(x,y):
    x_root,y_root=find_root(x),find_root(y)
    parent[x_root]=y_root

It has a wide range of uses, and the frequency of the test is also high. Think about it when you take the test.

Minimum spanning tree:

Applicable scenario: For a connected graph with n vertices, the connected subgraph with only n-1 edges is the minimum spanning tree

Often these n-1 edges are given weights and we need to find the minimum weight and

Board: There is a collection of content in it!


n=int(input())


edge=[]#edge[i]=[a,b,c]代表i这条边连接了a,b,权值为c

ans=0#权值和

edge.sort(key=lambda x:x[2])#按边权升序排序


for x in edge:#遍历所有边
    a,b,c=x[0],x[1],x[2]
    if find_root(a)!=find_root(b) and j<=n-1:#两顶点不连通且当前边数小于n-1
        ans+=x[2]#权值累加
        union(a,b)
        j+=1

print(ans)

Topological sort: 

Applicable scenarios: directed graphs, detection loops, and directed acyclic graphs must have topological sequences.

board:

graph={'a':'bc',
       'b':'ef'
    }
#graph的key表示入边,value表示被指向的点

indegrees=dict((i,0) for i in graph)
#初始化入度为0

for i in graph:
    for j in graph[i]:#遍历i的邻居 邻居入度+1
        indegrees[j]+=1

stack=[]#存入度为0的点
seq=[]#存拓扑序列

for i in indegrees:
    if indegrees[i]==0:#入度为0
        stack.append(i)#入栈

while stack:#栈不为空
    t=stack.pop(0)
    seq.append(t)
    for i in graph[t]:
        #邻居入度-1
        indegrees[i]-=1
        if indegrees[i]==0:
            stack.append(i)
            
if len(seq)==len(graph):
    #无环
else:
    #有环

Regarding DP, here is a direct reference to Xiaolan's notes, which is the first list this time~ Very well written!

[Dynamic programming] The content is very detailed, the blog on the left portal  small blue brush_

 Thank you for accompanying the Blue Bridge Cup all the way and thank you for your support to Xiao Zheng

I hope that tomorrow with my partner in the Python group, I will win the province and witness the national competition together!

May all your hard work pay off!

Guess you like

Origin blog.csdn.net/m0_62277756/article/details/123982233