Blue Bridge Cup Day 18 (Python Edition) (Day 1 of Crazy Writing)

Question type:

1. Thinking questions/Miscellaneous questions: Mathematical formulas, analyzing the meaning of questions, finding patterns

2. BFS/DFS: wide search (recursive implementation), deep search (deque implementation)

3. Simple number theory: modulus, prime number (only need to judge to  int (sqrt (n)) + 1 ), gcd, lcm, fast exponentiation (bit operation shift operation), large number decomposition (decomposition into the product of prime numbers)

4. Simple graph theory: shortest path (one-to-many (Dijstra, adjacent table, matrix implementation), many-to-many (Floyd, matrix implementation)), minimum spanning tree (and search set implementation)

5. Simple string processing: it is best to switch to list operations

6. DP: Linear DP, longest common subsequence, 0/1 knapsack problem, longest continuous string, largest increasing substring

7. Basic algorithms: binary, greedy, combination, permutation, prefix sum, difference

8. Basic data structures: queues, sets, dictionaries, strings, lists, stacks, trees

9. Commonly used modules: math, datetime, set the maximum recursion depth in sys (sys.setrecursionlimit(3000000)), collections.deque (queue), itertools.combinations (list, n) (combination), itertools.permutations (list, n) (permutation) heapq (small top heap)

Table of contents

real test questions

1. The trees in the university need to be sprayed (difference)

2. Trees in the university to maintain (prefix sum)

3. Results statistics (simple judgment)

4. Arrange letters (sort)

5. Paper size (loop statement)

6. Special time (thinking questions, hand calculation and enumeration according to requirements)

 7. Card questions (thinking questions, spell numbers to see which card is used the fastest)

8. Approximate numbers (examination of concepts)

9. Beautiful interval (violence method + sum function or double pointer or violence + prefix sum)

10. Palindrome judgment (string slicing or converting to list slicing)

11. Calculation of numbers (recursion, focusing on boundary processing and initial value setting)

12. Number division (DP, recursion, complete set splitting to find recursion relationship)

 13. Maze (BFS+DFS)

14. Jumping Grasshopper (BFS, custom enqueue element format, draw circle as straight)

15. Seven-segment code (drawing number)

16. Maze walk (BFS, entry information includes distance)

17. N queen problem


real test questions

1. The trees in the university need to be sprayed (difference)

 differential approach

import sys
import collections
import itertools
import heapq

n,m=map(int,input().split())
a=[0 for i in range(n+1)]  # 编号1-n
b =[0]+[a[i+1]-a[i] for i in range(0,n)] # 差分数组,编号1-n

for i in range(m):   # 整体区间操作直接对差分数组修改
    l,r,cost = map(int,input().split())
    b[l]+=cost;b[r+1]-=cost

for i in range(1,n+1):  # 根据差分数组重新还原数组
    a[i]=a[i-1]+b[i]
    
print(sum(a))

2. Trees in the university to maintain (prefix sum)

 

import sys
import collections
import itertools
import heapq

n,m=map(int,input().split())  # 马路的树木,区间的数目
cost = list(map(int,input().split()))
Pre_sum=[0]  # 记录前缀和,编号从1开始
temp=0
for i in range(n):  # 记录前缀和
    temp+=cost[i]
    Pre_sum.append(temp)
    
for i in range(m):  # 通过前缀和计算
    l,r=map(int,input().split())
    print(Pre_sum[r]-Pre_sum[l-1])
    

3. Results statistics (simple judgment)

 Send sub-questions, mainly for judging conditions, that is, two judging counts are enough, mainly for format output

print("{:.2%}".format(n)), keep two decimal places and output in percentage form

 format format usage

4. Arrange letters (sort)

 It is also a sub-question, mainly to understand the built-in sorting function, the sort() of the list, and the sorted() method of the iterable object

5. Paper size (loop statement)

The sub-question is mainly to extract information from the input, use string slices, and then halve the loop, and swap the length and width.

        a,b=b,a

6. Special time (thinking questions, hand calculation and enumeration according to requirements)

Fill-in-the-blank questions that have been tested will not be tested again, and the answer process will not be written. The idea of ​​​​solving the problem is that only the month and date, hour and minute need to be considered

Month: 1-12

Sun: 1-31

Hours: 0-23

Score: 0-59

Grab 3 identical hands and count the enumeration, the main thing is to be careful

 7. Card questions (thinking questions, spell numbers to see which card is used the fastest)

 It can be seen that 1 is the fastest to use. If you can’t see it, print it to see who is the fastest to use, and then directly create an endless loop. When card 1 is used up, use break to jump out of the loop.

8. Approximate numbers (examination of concepts)

 Divisible number: the number that can be divisible evenly, including 1 and itself, the remainder is 0 , because it is a fill-in-the-blank question, and the data is not very large, so you can directly loop, enumerate [1,1200000], or use large number decomposition, Decompose it into prime numbers, and then calculate the combination number of prime number powers.

9. Beautiful interval ( violence method + sum function or double pointer or violence + prefix sum )

import sys
import collections
import itertools
import heapq

#暴力
n,s =(map(int, input().split()))
a = [0]+list(map(int,input().split())) # 下标从1开始
ans=100000
##for i in range(1,n+1):
##    for j in range(i+1,n+1):
##        if sum(a[i:j+1])>=s:
##            ans=min(ans,j+1-i)
##print(ans)


#双指针
##left=1
##right=1
##ss=0  #记录区间值
##while right<=n: 
##    if ss<s: # 右移动
##        ss+=a[right]
##        right+=1
##    #if ss>=s:
##    else:
##        print(right,left)
##        ans=min(ans,right-left)  # right 指向后一个位置,所以没有+1
##        ss-=a[left]
##        left+=1
##print(ans)
##        


# 前缀和加暴力
pre=[0]  #记录前缀和
ss=0
for i in range(1,n+1):
    ss+=a[i]
    pre.append(ss)
for i in range(1,n+1):
    for j in range(i+1,n+1):
        if (pre[j]-pre[i-1])>=s:
            ans=min(ans,j+1-i)
print(ans)

This question is solved by 3 methods, double pointer is the best solution, followed by prefix sum, this question is to examine programming ability, without algorithm, it is violence, learn to use double pointer, fast and slow pointer, prefix sum to solve question.

10. Palindrome judgment (string slicing or converting to list slicing)

 Palindrome judgments are sent to sub-questions, which can be converted to lists in reverse order and output for comparison. The characters themselves can also be sliced, anyway, it’s a sub-question! ! ! str[::-1] list[::-1]

11. Calculation of numbers (recursion, focusing on boundary processing and initial value setting)

import sys
import collections
import itertools
import heapq
sys.setrecursionlimit(100000)

# 6
# 16 26 36
#    126 136
def f(x):
    global ans
    if x==1 or x==0:
        return
    for i in range(1,x//2 +1):
        ans+=1
        f(i)
    
n=int(input())
ans=1  # 自身是一个
f(n)
print(ans)

Recursive solution, the difficulty of this question lies in understanding the meaning of the question, a bit like a thinking question, pay attention to boundary processing, remember to declare the variable in the function as a global variable , and pay attention to the setting of the initial value, recursion pay attention to setting the maximum recursion depth ! ! !

12. Number division (DP, recursion, complete set splitting to find recursion relationship)

import sys
import collections
import itertools
import heapq
sys.setrecursionlimit(100000)


n, k = map(int, input().split())

# 初始化一个二维数组,用于存储 f(n, m)
dp = [[0 for j in range(210)] for i in range(210)]
for i in range(1, n+1):
   dp[i][1] = 1   # i个物品1个人分
   dp[i][i] = 1   # i个物品i个人分

for i in range(3, n+1):
   for j in range(2, k+1):
       if i > j:
           dp[i][j] = dp[i-j][j] + dp[i-1][j-1]  

print(dp[n][k])

There is a problem, isn't it that any two copies cannot be the same? ? The above methods are the same. If there is a problem with the title, what should be asked is how many ways there are! ! ! Solve by dp

 13. Maze (BFS+DFS)

01010101001011001001010110010110100100001000101010
00001000100000101010010000100000001001100110100101
01111011010010001000001101001011100011000000010000
01000000001010100011010000101000001010101011001011
00011111000000101000010010100010100000101100000000
11001000110101000010101100011010011010101011110111
00011011010101001001001010000001000101001110000000
10100000101000100110101010111110011000010000111010
00111000001010100001100010000001000101001100001001
11000110100001110010001001010101010101010001101000
00010000100100000101001010101110100010101010000101
11100100101001001000010000010101010100100100010100
00000010000000101011001111010001100000101010100011
10101010011100001000011000010110011110110100001000
10101010100001101010100101000010100000111011101001
10000000101100010000101100101101001011100000000100
10101001000000010100100001000100000100011110101001
00101001010101101001010100011010101101110000110101
11001010000100001100000010100101000001000111000010
00001000110000110101101000000100101001001000011101
10100101000101000000001110110010110101101010100001
00101000010000110101010000100010001001000100010101
10100001000110010001000010101001010101011111010010
00000100101000000110010100101001000001000000000010
11010000001001110111001001000011101001011011101000
00000110100010001000100000001000011101000000110011
10101000101000100010001111100010101001010000001000
10000010100101001010110000000100101010001011101000
00111100001000010000000110111000000001000000001011
10000001100111010111010001000110111010101101111000
import sys  #设置递归深度
import collections  #队列
import itertools  # 排列组合
import heapq
sys.setrecursionlimit(100000)

s="01010101001011001001010110010110100100001000101010 \
00001000100000101010010000100000001001100110100101 \
01111011010010001000001101001011100011000000010000 \
01000000001010100011010000101000001010101011001011 \
00011111000000101000010010100010100000101100000000 \
11001000110101000010101100011010011010101011110111 \
00011011010101001001001010000001000101001110000000 \
10100000101000100110101010111110011000010000111010 \
00111000001010100001100010000001000101001100001001 \
11000110100001110010001001010101010101010001101000 \
00010000100100000101001010101110100010101010000101 \
11100100101001001000010000010101010100100100010100 \
00000010000000101011001111010001100000101010100011 \
10101010011100001000011000010110011110110100001000  \
10101010100001101010100101000010100000111011101001 \
10000000101100010000101100101101001011100000000100 \
10101001000000010100100001000100000100011110101001 \
00101001010101101001010100011010101101110000110101 \
11001010000100001100000010100101000001000111000010 \
00001000110000110101101000000100101001001000011101 \
10100101000101000000001110110010110101101010100001 \
00101000010000110101010000100010001001000100010101 \
10100001000110010001000010101001010101011111010010 \
00000100101000000110010100101001000001000000000010 \
11010000001001110111001001000011101001011011101000 \
00000110100010001000100000001000011101000000110011 \
10101000101000100010001111100010101001010000001000 \
10000010100101001010110000000100101010001011101000 \
00111100001000010000000110111000000001000000001011 \
10000001100111010111010001000110111010101101111000"


vis=[[0]*60 for _ in range(60)]  # 标记是否访问过
fa=[['']*60 for _ in range(60)]  # 记录父结点
flag=['D','L','R','U']  # ↓x → y
##a = list(s.split(' '))
##print(a)
##ss=[]
##for i in s:  #转为2维列表
##    ss.append(i)
##print(ss)
ss=[]
for i in range(30):
    ss.append(list(map(int,input())))


def dfs(x,y):  # 通过DFS遍历找路径
    if x==0 and y==0:
        return
    if fa[x][y]=='D':dfs(x-1,y)
    if fa[x][y] =='L': dfs(x,y+1)
    if fa[x][y] =='R': dfs(x,y-1)
    if fa[x][y] =='U': dfs(x+1,y)
    print(fa[x][y],end='')
    
def bfs(x,y):
    global fa
    global vis
    deque=collections.deque()
    walk=[[1,0],[0,-1],[0,1],[-1,0]]  # 下,左,右,上
    vis[x][y]=1
    deque.append((0,0))  # 添加进队列
    while deque:
        x,y=deque.popleft()
        #print(x,y)
        if x==29 and y==49:
            print("找到终点!!")
            break
        for index in range(4):
            dx,dy=walk[index]
            nx=x+dx;ny=y+dy
            if 0<=nx<=29 and 0<=ny<=49 :
                if vis[nx][ny]==0 and ss[nx][ny]==0: # 坐标合法且没有走过
                    vis[nx][ny]=1
                    deque.append((nx,ny))
                    fa[nx][ny]=flag[index]

bfs(0,0)    
dfs(29,49)

The combination problem of BFS and DFS, when encountering the shortest path, BFS is generally used when the shortest path is encountered, and it is realized through the queue deque. For this kind of grid problem, generally ↓ is the x direction, and → has the y direction . Remember to set the marker array and record array to be larger.

BFS is implemented through loops, and DFS is implemented through recursion. 

14. Jumping Grasshopper (BFS, custom enqueue element format, draw circle as straight)

from collections import * 
def insertQueue(q: deque, dir: int, news: tuple, vis: set):
   pos = news[1];  status = news[0];  insertPos = (pos + dir + 9) % 9    
   t = list(status)
   t[pos], t[insertPos] = t[insertPos], t[pos]
   addStatus = "".join(t)
   if addStatus not in vis:
       vis.add(addStatus)
       q.append((addStatus, insertPos, news[2] + 1))  
q = deque()
q.append(("012345678", 0, 0))
vis = set();  vis.add("012345678")
while q:
   news = q.popleft()
   if news[0] == "087654321":      print(news[2]); break
   insertQueue(q, -2, news, vis);  insertQueue(q, -1, news, vis)
   insertQueue(q,  1, news, vis);  insertQueue(q,  2, news, vis)

The type of elements that enter the queue for BFS questions can be defined by yourself. Generally, it is combined with the needs of the topic, such as the minimum number of times, combined with the meaning of the question, combined with the meaning of the question, and combined with the meaning of the question.

15. Seven-segment code (drawing number)

 For hand calculation questions, calculate how many situations there are in turn according to the number of lights, and count by yourself by drawing pictures.

16. Maze walk (BFS, entry information includes distance)

import collections
mp = []   #存地图  n行m列
n,m = map(int,input().split())
for i in range(n):  # 读地图
    mp.append(list(map(int,input().split())))
x1,y1,x2,y2 = map(int,input().split())
dir = [(1,0),(0,-1),(0,1),(-1,0)]  # 下为x正方向,右为y正方向
vis = [[0]*200 for i in range(200)]  # 标记数组
ans = 0
flag=0
 
def bfs(x,y):
    global vis,ans,flag
    q = collections.deque()
    q.append((x,y,0)) # 遍历该点
    vis[x][y] = 1
    while q:
        now = q.popleft()
        if now[0]==(x2-1) and now[1] ==(y2-1) :# 到达终点(x2,y2)
            flag = 1
            ans=now[2]
            break
        for index in range(4):  # 4个方向遍历
            i=dir[index]
            nx = now[0]+i[0];ny = now[1]+i[1]
            if nx<0 or nx >=n or ny<0 or ny>=m : #超出了边界
                continue
            if vis[nx][ny]==1 or mp[nx][ny] ==0:  # 判断是否走过或者碰到了边界
                continue
            vis[nx][ny]=1
            q.append((nx,ny,now[2]+1))  # 将当前点添加进队列
bfs(x1-1,y1-1) # 从x1,y1搜索到x2,y2
if flag==0:
  print(-1)
else:
  print(ans)

 The combination of 12 questions and 13 questions is to find the minimum number of steps through BFS. The element format of the enqueue needs to have the number of steps each time, and it is enough to add one each time it is enqueued.

17. N queen problem

import sys  #设置递归深度
import collections  #队列
import itertools  # 排列组合
import heapq
sys.setrecursionlimit(300000)

n=int(input())

#vis = [[0]*11 for i in range(10)]  # 标记数组,下标从1开始
vis = [0]*11   # 标记是否使用过该列
ans = 0
save = [0]*11  # 记录每行放的位置,下标从1开始


def check(i,m):
   if vis[i]==1:  # 检查是否同列
      return False
   for j in range(1,m):  #遍历前面m-1个看是否斜对角相同
      if abs(m-j) ==abs(i-save[j]):
         return False
   return True
   
def dfs(m): # m行
   global ans,vis, save
   if m==n+1:
      print('Find')
      print(*save)
      ans+=1
      return
   for i in range(1,n+1):  # 遍历n列找位置
      if check(i,m):
         save[m]=i  # 第m行放在i列
         vis[i]=1   # 使用过第i列
         dfs(m+1)
         vis[i]=0

dfs(1)
print(ans)

 I have dealt with the subscript here, and changed the subscript to start from 1, which is more convenient to deal with. The dfs here does not use two dimensions for the tag array, but only uses one dimension to record the column, and judge whether the column has been used. Check whether the hypotenuse conflicts. An array is also used here to store the position of each placement. The judgment is used to judge the hypotenuse, and the output path can also be printed.

DFS template

vis=[ 0 ] * N array of tokens

def check()

        pass

def dfs()

        if (exit condition or endpoint reached):

                return

        for  i in choice:

             if check(i):

                protect the scene

                dfs()

                recovery site

Guess you like

Origin blog.csdn.net/weixin_52261094/article/details/129861955