ACWING python question every day during winter vacation (updated)

ACWING daily questions during winter vacation

Some of the questions are for the Lanqiao Cup. They have been written in previous articles and will not be written here again.

1. Photos of loneliness

insert image description here
Look at it point by point. For example, for the G in the middle of GHHGHG, find the positions of the G on the left and the G on the right. If l and r are equal to 1 respectively, the answer will be added by 1 1. But if for the G in the middle of
GHHGHG , we can see that l and r are equal to 2, so for a middle G, for its left half, l-1 photos can be taken, and for the right half, r-1 photos can be taken. After that, if the left and right sides are viewed together, they can be taken. l
r Zhang.
Once you know this, it’s easy to do it. We only need to store the coordinates of each G and H point, and then traverse the first series. However, we must pay attention to the boundary. For example, for the first G point, its l is equal to its coordinates. , then we only need to set G[0] to -1, so that when calculating l, it will be equal to G[1] (l = g[i] - g[i-1] -1)

The specific code is as follows

n = int(input())
s = input()
res = 0
g,h = [-1],[-1]  # 第一个点 h[1] - h[1-1]-1 就是h[1]
for i in range(n):
    if s[i] == 'G':
        g.append(i)  # 记录G的位置
    else:
        h.append(i)  # H的位置
g.append(n)  # 处理右边界, 最后一个点 h[i+1]-h[i]-1 
h.append(n)
for i in range(1,len(g)-1):
    l = g[i] - g[i-1] - 1 
    r = g[i+1] - g[i] - 1
    if l >= 2:
        res += l-1
    if r >= 2:
        res += r-1
    res += r*l
for i in range(1,len(h)-1):
    l = h[i] - h[i-1] - 1 
    r = h[i+1] - h[i] - 1
    if l >= 2:
        res += l-1
    if r >= 2:
        res += r-1
    res += r*l
    
print(res)

2. Number of statistics

insert image description here
It is not difficult for python, we have the count function, I don’t know about other languages, O(n) time complexity

code show as below

n,k = map(int,input().split())
res = 0
for i in range(1,n+1):
    i = str(i)
    k = str(k)
    res += i.count(k)
print(res)

3. Sleeping in class

insert image description here
insert image description here
For each set of data, we traverse the number of heaps from large to small, that is, how many heaps will be synthesized in total. Assuming it is a K heap, then the operation we need is nk. Because k is from large to small, what we find must be the operand Minimal.
Assuming it is divided into k piles, we must first determine whether the total sum % k is equal to 0. If it is not equal, it means that it cannot be divided into k equal parts, which will not work. If possible,
because only adjacent ones are merged, we traverse the piles from small to large, Set up a traversal mm to += w[i], w is a pile of stones, and then if it is equal to sum // k, let m return to 0, and continue to search. If m>sum//k, it will definitely not work, and then finally If m == 0, it means that the last synthesized pile is also equal to sum // k, and the pull is successful.

PS: It may be a bit confusing. Generally speaking, you need to traverse the pile of rocks, and then merge them from beginning to end, and merge them into sum//k. If you merge and merge and find that it is greater than sum//k, then it is definitely It doesn't work, because if you discard the first one, even if your pile can be equal to sum//k, your first one cannot be merged with other stones. Because there is either no stone in front of the stone at the beginning of the pile, or its front has been merged into sum//k.

#### 代码如下

def solve(w,cnt,totle):
    if totle % cnt != 0: return False# 如果总数不能除尽堆数,证明这个堆数是不可能的
    k = totle // cnt
    m = 0
    for i in range(len(w)):
        m += w[i]
        if m > k : return False
        if m == k : m = 0
    return m == 0    # 如果最后面刚好最后一堆的总和也等于平均数,就返回True
        



if __name__ == '__main__':
    t = int(input())
    for i in range(t):
        n = int(input())
        w = [int(x) for x in input().split()]
        totle = sum(w)
        for cnt in range(n,0,-1) : # 遍历堆数 就是要多最多的堆
            if solve(w,cnt,totle) : 
                print(n - cnt)     # 例如5堆最后分为3堆,就要操作5-2次
                break

4. Credit points

insert image description here
This question is also a relatively violent one, so there’s not much to say.

code show as below

if __name__ == '__main__':
    n = int(input())

    xuefen = [int(x) for x in input().split()]
    scores = [int(x) for x in input().split()]
    res = 0
    for i in range(n):
        if scores[i] >= 90:
            res += xuefen[i] * 4.00
        elif scores[i] >= 85:
            res += xuefen[i] * 3.7
        elif scores[i] >= 82:
            res += xuefen[i] * 3.3
        elif scores[i] >= 78:
            res += xuefen[i] * 3.0
        elif scores[i] >= 75:
            res += xuefen[i] * 2.7
        elif scores[i] >= 72:
            res += xuefen[i] * 2.3
        elif scores[i] >= 68 :
            res += xuefen[i] * 2.0
        elif scores[i] >= 64:
            res += xuefen[i] * 1.5
        elif scores[i] >= 60:
            res += xuefen[i] * 1.0
        else: res += 0
    print('{:.2f}'.format(res/sum(xuefen)))

5. Dairy University

insert image description here
Sort the tuition fee that each cow is willing to pay, and then traverse one by one, using the first, second... as the tuition fee to find the maximum value. It is very convenient to use enumerate. For example, use the third cow's willingness to pay The maximum price to do tuition, sum = tuition * (ni). Don’t worry if there are duplicates. For example, the maximum price you are willing to pay after sorting is 1 3 3 3... Then when calculating the first 3, it is the maximum amount of money that can be earned with a tuition fee of 3. The next two are not will overwrite the first 3

code show as below

if __name__ == '__main__':
    n = int(input())
    s = [int(x) for x in input().split()]
    
    s.sort()

    maxsum = 0
    finalmoney = 0
    for i,money in enumerate(s):
        sum = money * (n-i)
        if sum>maxsum:
            maxsum = sum
            finalmoney = money
    print(maxsum,finalmoney)

6. XOR of selected numbers

insert image description here
Direct violence will definitely cause TLE. We first preprocess an array maxl. maxl[i] represents the right boundary as i. What is the maximum tolerable left boundary? If l > maxl[r] in the end, say no, because You are bigger than the biggest I can tolerate.
So how to calculate this maxl? First, if the value of the XOR x of the i-th number is assumed to be b, maxl[i - 1] represents the maximum value that can be tolerated at the previous position, then should maxl[i] be equal to max ( maxl[i-1] , last position of b).
So now we only need to calculate the last position of the numbers that have appeared before, and then create an endpos to represent the last position of each number. When traversing, just let endpos[arr[i]] = i (arr is the original array)
and because l and r start from 1, our original array arr should also start from coordinate 1, at the first position Just add -1 to it.

The specific code is as follows

## a ^ b = x  --> a ^ x = b
N = 10**7
if __name__ == '__main__':
    n,m,x = map(int,input().split())
    endpos = [-1] * N
    arr = [-1]+[int(x) for x in input().split()]
    maxl = [-1] * (n+2)
    for i in range(1,n+1):
        # 对于每个位置来说,他能容许的左边的最大值(l 不能比这个再大了,可以在它的左边)是 maxl[i - 1] 或者 它目前这个位置的数异或值的最后一个位置
        maxl[i] = max(maxl[i-1] , endpos[arr[i]^x])  # arr[i] ^ x 是你这个点想要的那个b arr[i] ^ b = x,endpos[b] 就表示b出现的最后位置
        endpos[arr[i]] = i  # 记录一下每个数字出现的最后位置,每个重复数字都记录的是后面那个数字的下标
    
    for i in range(m):
        l,r = map(int,input().split())
        if (l != r and maxl[r] >= l):print('yes')
        else: print('no')

7. Summation

insert image description here
Once you figure it out, it's very simple. a1 will be multiplied by a2 a3 a4..., a2 will be multiplied by a3 a4...

Just look at the code

n = int(input())
a = [int(x) for x in input().split()]
sum1 = sum(a)
## 计算a1*a2+...a1*an+a2*a1+..a2*an...最后除以2
res = 0
for x in a:
    res += x*(sum1-x)
print(res >> 1)

8. Ranking by number (Blue Bridge Cup 2022)

9. Reorder

insert image description here
To calculate the largest sum after reordering, we only need to look at how many numbers have been added to each position, and then put the largest value in the position that has been added the most. How many numbers have been added to each position? The pass can be done with differencing. Put the largest value in the position where it has been added the most. You can sort the array and how many times each position has been added, so that one-to-one multiplication is OK.

The specific code is as follows

n = int(float(input()))
A = [int(x) for x in input().split()]
s = [0]*(n+1)
for i in range(1,n+1):
    s[i] = s[i-1] + A[i-1]
m = int(input())
C = [0]*(n+1) # 用来存储每个数被查询了几次,差分
sum0 = 0
for i in range(m):
    a,b = map(int,input().split())
        # for i in range(a-1,b):  # 数组中的下标要-1
        #     sum0 += A[i]
        #     C[i] += 1
    sum0 += (s[b] - s[a-1])
    C[a-1] += 1
    C[b] -=1
for i in range(1,n):
    C[i] += C[i-1]
C = C[:n]
A.sort()
C.sort()
sum1 = 0
for i in range(n):
    sum1 += C[i]*A[i]
print(sum1 - sum0)

10. Paper Size (Lanqiao Cup 2022)

11. Skill upgrade (Blue Bridge Cup 2022)

12. Uninitialized warning

insert image description here
insert image description here
I feel like there’s not much to say. Well, just look at the code. I’m sure you can understand it.

code show as below

n,k = map(int,input().split())
left = [] 
right = []
for _ in range(k):
    l,r = map(int,input().split())
    left.append(l)
    right.append(r)
res = 0
for i in range(k):
    r = right[i]
    if i == 0 and r != 0 : 
        res += 1
        continue 
    if r == 0:continue
    if r not in left[:i] : res += 1
print(res)

13. Normalization processing

insert image description here
This question is very simple for Python. It doesn't need to consider the number of decimal places or anything like that, just do it directly.

code show as below

import math
n = int(input())
A = [int(x) for x in input().split()]
a = sum(A) / n
d = 0
for i in range(n):
    d += (A[i] - a) ** 2
d = d/n
sqrtd = math.sqrt(d)
for i in range(n):
    print((A[i] - a) / sqrtd )

14. Encoding like this

insert image description here
insert image description here
insert image description here
As you can see, m % c1 // c0 will be equal to b1. So what is b2 equal to?
b2 = m % c2 // c1 within one digit c0*b1 = m % c1 He must not be greater than c1, so he can be ignored. In this case, it is easy to do.
We only need to record a ci and a c(i- 1) Just pull it

The specific code is as follows

n,m = map(int,input().split())
a = [int(x) for x in input().split()]
b = []
c = 1 # c0 = 1
tc = 1
for i in a:
    tc = i*c  # 第一次是c1,c是c0,第二次t是c2,c是c1,以此类推
    b.append((m%tc) // c)
    c = tc
print(*b)

15. Why free shipping?

insert image description here
We use f[j] to indicate whether the plan with price j exists. If it exists, it is 1. Otherwise, it is 0. After that,
we only need to traverse the array of prices of our books, from large to his price, so that f[j] |= f[j - w[i]], people from big to small will not buy the same book. f[j - w[i]] is 1, then it means that we can buy the book w[i], so that f[j] = 1

The specific code is as follows

# f[i]表示价格为i的方案是否存在
n,x = map(int,input().split())
w = []
for _ in range(n):
    money = int(input())
    w.append(money)

maxxx = 3*10**5 + 10
f = [0]*(maxxx + 1000)
f[0] = 1
for i in range(n):
    for j in range(maxxx,w[i]-1,-1):
        f[j] |= f[j - w[i]]
for i in range(x,maxxx+1):
    if f[i] == 1:
        print(i)
        break 

16. Travel plan

insert image description here
insert image description here
Borrowing the explanation from the boss
insert image description here
, that is to say, for the i-th place, if q is within a range from ti - k - ci +1 to ti - k, it means that you can go to this place.
Then we can use the difference. For each location, we add 1 to the number of the d array from ti - k - ci +1 to ti -k. Finally, we only need d[q].

The specific code is as follows

n,m,k = map(int,input().split())
N  = 10 ** 6
d = [0] * N
for _ in range(n):
    t,c = map(int,input().split())
    d[max(1,t-k-c+1)] += 1
    d[max(1,t-k+1)] -= 1

for i in range(1,N):
    d[i] +=d[i-1]     # 前缀和

for _ in range(m):
    q = int(input())
    print(d[q])

Seventeen. Treasure hunt! big Adventure!

insert image description here
insert image description here
We can record the points of each tree in the greening map. Remember not to draw the map directly, otherwise it will burst the memory if it is too large.
Then because the lower left corner of the treasure map must be the lesson tree, we can traverse all the trees in the green map, and then extend it to see if it matches. It is relatively simple to traverse i and j. The length is s. If the treasure is hidden If the graph [i][j] is 1, then find out whether there are trees in the corresponding greening graph.

The specific code is as follows

n,l,s = map(int,input().split())
# green = [[0]*(l+1) for _ in range(l+1)]  # 直接建立个列表会超内存,因为要建立10**p * 10**9 的列表 太大了
treasure =  [[] for _ in range(s+1)]
tree = []
map1={}     # map1跟tree作用差不多,但是后面要找元素是否在map1中,这比找是否在tree中快
for _ in range(n):
    x,y = map(int,input().split())
    tree.append((x,y))
    map1[(x,y)]=1
    # green[x][y] = 1
for i in range(s+1):
    a = [int(x) for x in input().split()]
    treasure[s-i] = a
res = 0

for x,y in tree:
    flag = 0
    for i in range(s+1):
        for j in range(s+1):
            if x + i > l or y + j > l : 
                flag = 1
            if treasure[i][j] :
                if (x+i,y+j) not in map1:
                    flag = 1
                    break
            else: 
                if (x+i,y+j) in map1:
                    flag = 1
                    break
                
        if flag == 1:break
    if flag == 1:continue
    else : res += 1

print(res)

18. Left child, right brother (Lanqiao Cup 2021)

Nineteen, exponentiation

insert image description here
This is also relatively simple, just look at the code.

The specific code is as follows

a,b = map(int,input().split())
res = 1
for _ in range(1,b+1):
    res *= a
    if res > 1000000000 :
        print(-1)
        break
if res <= 1000000000:print(res) 

20. Decryption

insert image description here
insert image description here
Just look at the mathematical derivation of the boss moyou. . It's too strong.
insert image description here
Just write it directly based on these formulas. .

The specific code is as follows

from math import sqrt 
for _ in range(int(input())):
    n,d,e = map(int,input().split())
    m = n - d*e + 2
    delta = m*m - 4*n
    if delta < 0:
        print('NO')
    else:
        x = sqrt(delta)
        if x == int(x):
            up1 = m - x
            up2 = m + x
            if up1 % 2 == 0 and up2 % 2 == 0:
                print(int(up1 / 2), int(up2 / 2))
            else:
                print('NO')
        else: print('NO')

Guess you like

Origin blog.csdn.net/abc1234564546/article/details/129033027