Blue Bridge Cup Series 1——Python group real questions

zero

After the replay of the exam, I think that the practice questions have improved the fastest. This may be different for everyone, just for reference.
But in the early stage, you can practice first and do small problems to lay the foundation. At the beginning, I wrote Yang Hui triangle directly. I wrote it for almost a whole day. Later, after practicing the small questions, I could do two questions in one afternoon|ू・ω・` )

one

This blogger sorted out almost all the topics and codes of the Blue Bridge Cup in the Python group U•ェ•*U, and the unlock column only costs 10r, which is great value for money. If you have plenty of time, or want to hit the top of the province, you can support ᕦ(・ㅂ・)ᕤ
https://bigsmart.blog.csdn.net/article/details/103641497

two

When I look at the code, I can’t see it o(╥﹏╥)o, so when I read the above blog, I mainly look at the ideas, and then I type it again by myself. His thoughts are really seconds, amazing. But some of them did not have full marks. I asked the teachers of the college to help me get the answers. It seems that the teacher port of the Lanqiao Cup system has marked answers. If there are no other questions, you can ask the teacher in charge.

three

The part of practicing the real questions is the part that took me the longest, because the nature of the python language determines that it is difficult to get full marks for violent algorithms, so it took a long time to optimize the version, but this part is also the biggest gain.

real question type

String algorithm, sorting algorithm, recursion, prim algorithm of minimum spanning tree, dfs algorithm, greedy algorithm, dynamic programming

PREV-282 Yang Hui Triangle【The Twelfth Session】【Provincial Competition】【Group B】

topic

insert image description here

reference

https://blog.csdn.net/weixin_44091134/article/details/116748883

Version 1 score 20

# 杨辉三角 超时了得分:20
def output(n):
    if n == 1:
        return 1
    else:
        sanjiao=[]
        for i in range(n):
            sanjiao.append([1 for _ in range(i+1)])
            if i >= 2:
                for j in range(1,i):
                    sanjiao[i][j]=sanjiao[i-1][j-1]+sanjiao[i-1][j]
                    if sanjiao[i][j] == n:
                        result=(1+i)*i/2+j+1
                        print(sanjiao)
                        return result   

N=int(input())
print(int(output(N)))
20
[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1], [1, 5, 10, 10, 5, 1], [1, 6, 15, 20, 1, 1, 1]]
25

Version 2 Score 40

# 杨辉三角 二项式定理 M=C(N,i)=n!/((n-i)!i!) 超时了 得分:40
# (sanjiao[i][j]=i!/((i-j)!j!)
import math 

row = 3
max1 = 1
while True:
    if row%2 !=0:
        max1 = 2*max1
    else:
        max1 = 2*max1*(row-1)//row
    print(row,max1)
#     if max1>515927503:
#         print(row)
    row = row+1
    if row >11:
        break

3 2
4 3
5 6
6 10
7 20
8 35
9 70
10 126
11 252

Version 3 standard answer 100 points

def C(a,b): # 计算组合值
    res=1
    tmp=a
    for j in range(1,1+b):
        res=res*tmp//j #累除取余j
        if res > n:
            return res  #大于n已无意义,且防止爆LL
        tmp = tmp -1
    return res

def check(k):
    # 二分该斜行,找到大于等于该值的第一个数
    # 左边界2k,右边界为max(l, n)取二者最大,避免右边界小于左边界
    l,r=k*2,max(1,n)
    while l<r :
        mid =l+r >>1
        # print(mid,k)
        if C(mid ,k)>=n:
            r=mid
        else:
            l=mid+1
    if C(r,k)!=n:
        return False
    print(r*(r+1)//2+k+1)
    return True

n=int(input())
if n==1:
    print(1)
else:
    k=16 # 从第16斜行枚举
    while not check(k):
        k=k-1
6
13

PREV-279 Time Display【The Twelfth Session】【Provincial Competition】【Group B】

topic

insert image description here

score 100

n=int(input())
n = n / 1000
H = n // (60*60)
M = (n-H*3600)//60
S = n%60
if H > 24:
    H = H % 24
print('%.2d:%.2d:%.2d'%(H,M,S))
1111111
00:18:31

test

print(3//2)
print(int(3/2))
print('%.2d:%.2d:%.2d'%(13,0,1)) #%.2d格式化输出两位整数
1
1
13:00:01

PREV-276 Two-way sorting【The Twelfth Session】【Provincial Competition】【Group B】

topic

insert image description here

Version 1 score 60

# 超时 得分60
def sheng(num,x):
    a = sorted(num[x-1:])
    num[x-1:]=a
#     print(num)
    return num

def jiang(num,x):
    b = sorted(num[:x],reverse=True)
    num[:x]=b
    return num

n,m=map(int,input().split())
num=[i+1 for i in range(n)]
for i in range(m):
    p,q=map(int,input().split())
    if p == 0:
        num = jiang(num,q)
    else:
        num = sheng(num,q)
for i in range(n):
    print(num[i],end=' ')
3 3
0 3
[3, 2, 1]
1 2
[3, 1, 2]
0 2
[3, 1, 2]
3 1 2 

error-prone

number[x-1:x]

Left closed right open (x-1,x-1)

Version 2 markup

if __name__ == '__main__':
	n, m = map(int, input().split())
	nums = [i + 1 for i in range(n)]
	seq = []  # 用于存储操作序列
	for _ in range(m):
		p, q = map(int, input().split())
		if p == 0:
			while seq and seq[-1][0] == 0:  
				q = max(q, seq[-1][1])
				seq.pop()
			while len(seq) > 1 and seq[-2][1] <= q:  
				seq.pop()
				seq.pop()
			seq.append((0, q))
		elif seq:  
			while seq and seq[-1][0] == 1: 
				q = min(q, seq[-1][1])
				seq.pop()
			while len(seq) > 1 and seq[-2][1] >= q:  
				seq.pop()
				seq.pop()
			seq.append((1, q))

	k, left, right = n, 1, n
	for i in range(len(seq)):
		if seq[i][0] == 0:  # 前缀降序
			while right > seq[i][1] and left <= right:
				nums[right - 1] = k		# 从后往前设置
				right -= 1
				k -= 1
		else:  # 后缀升序
			while left < seq[i][1] and left <= right:
				nums[left - 1] = k		# 从前往后设置
				left += 1
				k -= 1
		if left > right:
			break

	if len(seq) % 2:   # 最后一次操作为前缀降序
		while left <= right:
			nums[left - 1] = k
			left += 1
			k -= 1
	else:				# 最后一次操作为后缀升序
		while left <= right:
			nums[right - 1] = k
			right -= 1
			k -= 1

	print(' '.join(map(str, nums)))
3 3
0 3
1 2
0 2
3 1 2

PREV-271 Bracket sequence [The 12th session] [Provincial competition] [Group B]

topic

insert image description here

Strategy

No, you can just give up if you encounter it later


PREV-263 Weighing with Weights【The Twelfth Session】【Provincial Competition】【Group B】

topic

insert image description here

test

a = [[0 for _ in range(3)]for _ in range(2)]
print(a)
[[0, 0, 0], [0, 0, 0]]

Version 1 score 80

# 超时 得分80
n = int(input())
array = list(map(int, input().split()))

sum1 = sum(array)
a_len = len(array)
ans = 0
dp = [[0 for i in range(sum1+1)] for j in range(a_len)]

dp[0][array[0]]=1 # no1

for i in range(1,a_len):
    for j in range(1,sum1+1):
        dp[i][j]=dp[i-1][j] # copy 对于当前的复制前一个的重量
    dp[i][array[i]]=1 # 当前状态是可称的
    for j in range(1, sum1+1): # 最大重量为所有砝码重量总和
        if(dp[i-1][j]): #pre=1 上一个状态的重量
            dp[i][j+array[i]] = 1 # 上一状态的重量在加上当前重量
            dp[i][abs(j-array[i])]=1 # 上一个状态的重量减去当前状态的重量

for i in range(1,sum1+1):
    if(dp[n-1][i]):
        ans += 1

print(ans)
# print(dp)
3
1 4 6
10

Version 2 markup

n = eval(input())
weights = [eval(x) for x in input().split()]

def solution(weights):
	counts = set()
	for weight in weights:
		to_add = []
		to_add.append(weight)
		for count in counts:
			same = weight  + count
			different = abs(weight - count)
			if same not in counts:
				to_add.append(same)
			if different not in counts:
				to_add.append(different)
		for new_count in to_add:
			counts.add(new_count)
	result = len(counts)
	if 0 in counts:
		return result -1 
	return result

print(solution(weights))
3
1 4 6
10

PREV-226 Palindrome Date【Eleventh Session】【Provincial Competition】【Group B】

topic

insert image description here

problem solving ideas

Need to give the next palindromic date of the input date and the next ABABBABA type date.
So start from the input number, +1 each time through the loop.

Use date to represent the number entered.
The first number output needs to judge whether the date is a legal date and a palindrome number.
In addition to the above judgment, the second output number also needs to judge whether it is an ABABBABA type number.

We can use 3 functions to judge the above three conditions

1. Judging whether it is a legal date
To judge whether a number is a legal date, you only need to see whether the month and the number of days are legal, for example:
1, 3, 5, 7, 8, 10, and December have 31 days;
4, 6, September and November have 30 days;
February needs to be judged separately. If the year is a leap year, February has 29 days; otherwise, February has only 28 days.

2. Determine whether it is a palindrome

Method 1: Determine whether they are equal after directly reversing a number

Method 2:
Convert numbers to strings, and define two pointers at the left and right ends.
Judging whether the characters at the left and right ends are the same, if they are the same, move the left and right pointers one bit inward, and judge in turn.
As long as one bit is different, false can be returned directly.
When the two pointers meet, it means that all the characters in the string have been compared, and if there is no need to be different, return true.

3. Judging the type of ABABBABA

Method 1:

Directly decompose this number to "forcibly" judge

Method 2:
Just judge whether the 0, 2, 5, 7 bits of the string are the same, and whether the 1, 3, 4, 6 bits of the string are the same

reference

https://blog.csdn.net/ZZZWWWFFF_/article/details/122867786

a=['01','02','03','04','05','06','07','08','09','10','11','12']#月份
b=['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31']#日期
s=[]
for i in range(1000,9000): # 月份+日期
    if str(i)[::-1][:2] in a and str(i)[::-1][2:] in b: # a是月份,b是日期
        # print(str(i),str(i)[::-1])
        s.append(str(i)+str(i)[::-1]) # str(i)[::-1]为回文年份
        
for i in s:#去除不合法二月日期
    if i[4:6]=='02':
        if int(i)%400!=0 and int(i[6:])>28:
            s.remove(i)
        if int(i)%400==0 and int(i[6:])>29:
            s.remove(i)
big=['01','03','05','07','08','10','12']
small=['02','04','06','09','11']
for i in s:#去除不合法大小月
    if i[4:6] in small and int(i[6:])>30:
        s.remove(i)
    if i[4:6] in big and int(i[6:])>31:
        s.remove(i)
        
N=int(input())
for i in s: # 判断回文日期
    if int(i)>N:
        print(i)
        break
for j in s: # 判断 ABABBABA 型数
    if int(j)>N and j[:2]==j[2:4] and j[0]!=j[1]:
        print(j)
        break
20200202
20211202
21211212
print(str(i)[::-1][:2]

symmetrical maze

topic

describe

wlxsq has an N*NN∗N grid maze, and each grid has a letter number.

He wants to start from the upper left corner (1,1)(1,1) and go to the lower right corner (n,n)(n,n). Since wlxsq is lazy, he will only go to the right or down one step at a time. grid.
Since there are too many path schemes from the end to the end, wlxsq wants you to calculate the number of all different symmetrical paths.
For example: N = 3N=3
ABA
BBB
ABA
6 symmetrical paths: ABABA (2), ABBBA (4)
Different symmetrical paths: ABABA, ABBBA

Input
Enter a number NN in the first line, indicating the size of the maze.
Next, enter the letter maze of N*NN∗N

Output
Number of output symmetric paths

Example
3
ABA
BBB
ABA

output
2

Prompt
[Evaluation use case scale and agreement]
For 40%40% of the data, 2<=N<=112<=N<=11

For 100%100% data, 2<=N<=182<=N<=18

train of thought

In this kind of problem, it is generally searched deeply first and then save all the paths, then judge whether it is a symmetrical path, and then judge the weight, but this is a completely violent method, which will not only timeout, but also burst the memory. The graph that approximates the maximum is that the 18th road force has about 2^18 power bars.
Optimize it as much as possible, so there is a second way of thinking.
Search twice, the first search from 1,1 position, the second search from n,n position, save the path and the end point respectively, and then compare whether the end point is the same, whether the path is the same, the path strength here is also a Very large data, and with weight judgment, if the optimization is not good, it will time out.
A visit array can be used to judge the weight of numbers, and a map can be used to judge paths.

reference

https://blog.csdn.net/weixin_45483201/article/details/104255693

the code

from collections import defaultdict

dx=[1,0,-1,0]
dy=[0,1,0,-1]

dic=defaultdict(int)
n=int(input())

def dfs1(x,y,step,path):   
    if x+y==n-1:
        dic[path]=1
        vis[x][path]=1
        return
    
    for i in range(0,2):
        if x+dx[i]<n and x+dx[i]>=0 and y+dy[i]<n and y+dy[i]>=0 :
            dfs1(x+dx[i],y+dy[i],step+1,path+mp[x+dx[i]][y+dy[i]])
        
ans=int(0)

def dfs2(x,y,step,path):
    global ans
    
    if x+y==n-1:
        if dic[path]==1 and vis[x][path]==1 :
            ans+=1
            dic[path]=0
        return
    
    for i in range(2,4):
        if x+dx[i]<n and x+dx[i]>=0 and y+dy[i]<n and y+dy[i]>=0 :
            dfs2(x+dx[i],y+dy[i],step+1,path+mp[x+dx[i]][y+dy[i]])      

mp=[str("") for i in range(n)]
vis=[defaultdict(int) for j in range(n)]
for i in range(0,n):
    mp[i]=input()

dfs1(0,0,1,""+mp[0][0])
dfs2(n-1,n-1,1,""+mp[n-1][n-1])
print(ans)
3
ABA
BBB
ABA
2

Guess you like

Origin blog.csdn.net/wtyuong/article/details/124547334