[Blue Bridge Cup Zhenti] 16-day sprint Python

The competition is soon, and I hope that the PY party I prepared with me can master Python more proficiently! 

 1. Distance and (fill-in-the-blank questions)

Problem Description:

The distance between two letters is defined as the distance between their positions in the alphabet. For example, the distance between A and C is 2, and the distance between L and Q is 5.

For a string, we call the sum of the distances between two characters in the string the internal distance of the string.

For example: ZOO the inner distance is 22, where the distance between ZZ and OO is 11.

Excuse me, what LANQIAO is the internal distance?

s=input()

ans=0
for i in range(len(s)):
    for j in range(i+1,len(s)):
        ans+=abs(ord(s[i])-ord(s[j]))
print(ans)

Topic Analysis:

It is to examine an Ascii code, and the absolute value of the difference between the two letters Ascii is the distance 

Two layers of loop traversal and accumulation can be


2. Diffusion 

This question is a fill-in-the-blank question. After calculating the result, use the output statement in the code to output the filled result.

Xiao Lan paints on a special canvas of infinite size.

This canvas can be seen as a grid, and each grid can be represented by a two-dimensional integer coordinate.

Xiaolan first clicked a few points on the canvas: (0, 0), (2020, 11), (11, 14), (2000, 2000)

Only these grids are black, the rest are white.

Every minute that passes, the black spreads out a little bit. Specifically, if a grid is black, it will spread to the four adjacent grids up, down, left, and right, so that these four grids also become black (if they were originally black, they are still black).

Excuse me, after 2020 minutes, how many grids are black on the canvas.

Topic Analysis:

To investigate a multi-source BFS, you can learn from the ACwing simulation competition farmland irrigation problem, the same, I wrote a detailed analysis in this blog: [Blue Bridge Cup Zhenti] 18-day Python team sprint experience summary_Py Xiaozheng's blog -CSDN Blog

However, for this question, if the PY partner uses an ordinary list to simulate the queue, it will not be able to run, it is too slow.

Because the complexity of list deletion and insertion is O(n), the amount of data is large.

You need to use the deque (two-way queue) in the library that comes with PY. Its time complexity is O(1), and it can run out in half a minute.

The most important thing to pass this question is to learn to use deque to help us improve the speed!

collections.deque learning portal:  detailed explanation of deque() of Python collections module - Programmer Sought

import collections

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

pre={(0,0):(0,0),(2020, 11):(2020,11),(11, 14):(11, 14),(2000, 2000):(2000, 2000)}
ans=4
queue=collections.deque()
queue.append((0,0,0))
queue.append((2020, 11, 0))
queue.append((11, 14, 0))
queue.append((2000, 2000, 0))

while queue:
    t=queue.popleft()
    if t[2]==2020:
        print(ans)
        break
    else:
        for i in range(4):
            nx,ny=t[0]+dx[i],t[1]+dy[i]
            if (nx,ny) not in pre.keys():
                pre[(nx,ny)]=(t[0],t[1])
                queue.append((nx,ny,t[2]+1))
                ans+=1
#扩散 20312088
                

3. Wrong ticket 

You can see the first question of my article 

Blue Bridge Cup preparation practice python impact province one - Py Xiaozheng's Blog - CSDN Blog

4. Multiple problem

As we all know, Xiao onion is good at calculation, especially good at calculating whether a number is a multiple of another number. But shallots are only good at two numbers, and when there are many numbers, they will be more distressed. Now the onion has given you n numbers, and I hope you can find three numbers from these n numbers, so that the sum of these three numbers is a multiple of K, and this sum is the largest. The data guarantees that there must be a solution.

enter description

The first line contains 2 positive integers n, K.

The second line contains n positive integers representing the given n numbers.

output description

One line of output is an integer representing the desired sum.

Topic Analysis: 

This question needs to be explained well, because Xiao Zheng has also studied it for a long time, and he didn't solve it last time...

Special thanks to a good brother of mine here

 Blue Bridge Multiple Problem Enumeration Optimization

I learned a lot of my ideas from him, so many of the following analysis will quote his original words (because he speaks so well!)

First of all, the violent method, the 3-layer for loop must be timed out, indicating that the method needs to be changed.

Let x+y+z=nk (x,y,z,n,k>0), then there must be

(x%k+y%k+z%k)%k=0 (obtained according to the algorithm )

The problem is transformed into, knowing that the original n numbers form a set A, and then taking the remainder of each number to form a new set B, in the set B, take 3 elements so that their sum is a multiple of k, and the remainder The corresponding elements in set A are added and the sum is the largest.

We might as well set a dictionary dic[i]=[x,y,z...]: representing the numbers x, y, z.. The result of taking the remainder of k is i

Since we always want to take a larger number, we might as well sort the set A in descending order (from large to small), so that the remainder of all numbers is put into the dictionary, and the list corresponding to each key must be from large to small. of.

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

a=list(map(int,input().split()))
a.sort(reverse=True)
b=dict()

for i in range(len(a)):
    r=a[i]%k
    if r not in b.keys():
        b[r]=[a[i]]
    else:
        b[r].append(a[i])

Set the answer to ans, the initial value is 0, the next step is to find the remainder combination (satisfying the sum is a multiple of k), and update ans

If the first two remainders i,j are enumerated, then the third remainder t is uniquely determined , no need for three layers of loops (reduce loop optimizer as much as possible)

The reason is as follows, if i, j, t are all elements of set A obtained by taking the remainder of k, it is necessary that i, j, t all satisfy the range (0, k)

Then i+j+t must satisfy the range (0,3k), then i+j+t= k or 2k is in line with the meaning of the question

And i+j satisfies the range (0,2k), then when 2k>i+j>k, t=2k-ij,

When 0<i+j<k, t=kij, for a set of i, j, the range of i+j is determined, so the third remainder t is uniquely determined

for i in range(k):
    for j in range(k):
        t = k-i-j if (i+j)<= k else 2*k-i-j

Then update ans.

For 3 remainders, there are no more than three cases, three remainders are the same, two remainders are the same, and one remainder is the same (mutually different)

If the three remainders are the same, and the length of the list (number of elements) corresponding to this remainder is >=3, then it is a feasible solution, otherwise there is no solution, because no three numbers can be made up

If the two remainders are the same , and the length of the list (number of elements) corresponding to this remainder is >=3, and the length of the list (number of elements) corresponding to the third remainder (different from these two) is >=1 (that is, non-empty), then it is a feasible solution, otherwise there is no solution

If one of the remainders is the same, as long as the list corresponding to the three mutually different remainders is not empty, there is a feasible solution.

Then keep comparing ans with feasible solutions, and ans is constantly updated and larger. In fact, in the case where the two remainders are the same, it can be divided into 3 types, because it can be 12, 13, 23.

for i in range(k):
    for j in range(k):
        t = k-i-j if (i+j)<= k else 2*k-i-j
        if i==j==t:
            if len(b[t])>=3:
                ans=max(ans,b[t][0]+b[t][1]+b[t][2])
        elif i==j:
            if len(b[i])>=2 and len(b[t])>=1:
                ans=max(ans,b[i][0]+b[i][1]+b[t][0])
        elif i==t:
            if len(b[i])>=2 and len(b[j])>=1:
                ans=max(ans,b[i][0]+b[i][1]+b[j][0])
        elif j==t:
            if len(b[j])>=2 and len(b[i])>=1:
                ans=max(ans,b[j][0]+b[j][1]+b[i][0])
        else:#三个互异
            if len(b[i])>=1 and len(b[j])>=1and len(b[t])>=1:
                ans=max(ans,b[i][0]+b[j][0]+b[t][0])

 The key error is reported, because the key does not exist, so when the remainder is not in b, the next cycle can be performed directly

for i in range(k):
    for j in range(k):
        t = k-i-j if (i+j)<= k else 2*k-i-j
        if i not in b or j not in b or t not in b:
            continue
        if i==j==t:
            if len(b[t])>=3:
                ans=max(ans,b[t][0]+b[t][1]+b[t][2])
        elif i==j:
            if len(b[i])>=2:
                ans=max(ans,b[i][0]+b[i][1]+b[t][0])
        elif i==t:
            if len(b[i])>=2:
                ans=max(ans,b[i][0]+b[i][1]+b[j][0])
        elif j==t:
            if len(b[j])>=2:
                ans=max(ans,b[j][0]+b[j][1]+b[i][0])
        else:#三个互异
            ans=max(ans,b[i][0]+b[j][0]+b[t][0])

To sum up the code

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

a=list(map(int,input().split()))
a.sort(reverse=True)
b=dict()

for i in range(len(a)):
    r=a[i]%k
    if r not in b.keys():
        b[r]=[a[i]]
    else:
        b[r].append(a[i])

ans=0

for i in range(k):
    for j in range(k):
        t = k-i-j if (i+j)<= k else 2*k-i-j
        if i not in b or j not in b or t not in b:
            continue
        if i==j==t:
            if len(b[t])>=3:
                ans=max(ans,b[t][0]+b[t][1]+b[t][2])
        elif i==j:
            if len(b[i])>=2:
                ans=max(ans,b[i][0]+b[i][1]+b[t][0])
        elif i==t:
            if len(b[i])>=2:
                ans=max(ans,b[i][0]+b[i][1]+b[j][0])
        elif j==t:
            if len(b[j])>=2:
                ans=max(ans,b[j][0]+b[j][1]+b[i][0])
        else:#三个互异
            ans=max(ans,b[i][0]+b[j][0]+b[t][0])
print(ans)

If it's helpful to you, is it okay to stay for three consecutive years!

If you have any questions, please ask in the comment section!

Guess you like

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