The second day of learning python --- difference

1. Change array elements (difference)

insert image description here

Method 1: Difference array

map(int,input().split())

This returns an object, not an integer

for b in arr[:n]:

arr[:n] is a slice operation in Python that represents the sublist from the beginning (index 0) to the n-1th element of the list arr.

print(1 if b else 0,end=’ ')

What this code does is convert the Boolean value b into an integer and print it out. If b is True, print 1, otherwise print 0. The end=' ' in the code means that the printed result will not be wrapped, but ended with a space.

#只用关心某个数字位置是否被覆盖过,不关心覆盖过几次
for i in range(int(input())):#读入输入数组的次数
    n,a=int(input()),list(map(int,input().split()))#前面是传入一个数,后面传的一个数组
    arr=[0]*(n+5)#数组的大小
    for j in range(n):
        arr[max(0,j-a[j]+1)]+=1
        arr[j+1]-=1
    for j in range(1,n):
        arr[j]+=arr[j-1]#差分数组
    for b in arr[:n]:
        print(1 if b else 0,end=' ')#这个用法好绝,对于初学者来说
    print()#换行

Method 2: Interval Merging

This code is an algorithm for dealing with interval problems, which mainly implements the following steps:

1. Read in an integer n and an integer list a of length n.

2. For each element a[j] in the list a, if it is not zero, add the interval [max(0, ja[j]+1), j] to the interval list.

3. Sort the interval list according to the left endpoint of the interval.

4. For each interval in the sorted interval list, mark all elements in the interval as 1 in the arr list.

5. Output the marked arr list.

It can be seen that the time complexity of the algorithm is O(nlogn), and the most time-consuming operation is sorting the range list.

interval.sort(key=lambda x:x[0])

This code is sorted according to the left endpoint, if you want to sort according to the right endpoint

interval.sort(key=lambda x: x[1])

for i in range(int(input())):#input()返回为str,转换为int
    n,a=int(input()),list(map(int,input().split()))#输入数组大小及数组元素
    arr,interval=[0]*n,[]
    for j in range(n):
        if a[j]:
            interval.append([max(0,j-a[j]+1),j])#记录区间
    interval.sort(key=lambda x:x[0])#按照区间端点进行排序
    if interval:#检查interval是否为空,若为空则直接输出长度为n的全0数组,
        # 如果不为空,则按照一定的规则将1填充到arr数组中
        p=1#编号为0的区间
        for j in range(1,len(interval)):
            if interval[j][0]>interval[p-1][1]+1:#如果区间左端点大于编号为p-1的一个区间右端点+1,则说明这是两个区间
                interval[p]=interval[j]
                p+=1
            else:#如果在内部,则可以这两个区间
                interval[p-1][1]=max(interval[p-1][1],interval[j][1])
        for j in range(p):#枚举每个区间,将每个区间内所包含的置1
            for k in range(interval[j][0],interval[j][1]+1):
                arr[k]=1
    for a in arr:
        print(a,end=' ')
    print()

Note the indentation! ! !

Second, the difference

insert image description here

a = [0] + list(map(int, input().split())) + a[n + 1:]

The function of this line of code is to replace the elements from subscript 1 to n (including 1 and n) in the list a with the input elements, and add a 0 at the beginning and end of the list to ensure that subsequent operations will not appear Index error. specifically:

a[:n+1] means the elements from subscript 0 to n, where a[0] is the first element of the list, a[n] is the last element of the list, a[n+1:] means from All elements from subscript n+1 to the end of the list.

Therefore, the effect of a = [0] + list(map(int, input().split())) + a[n +1:] is to first add 0 to the beginning of the list, and then add the input elements to At the original position, finally add all elements from the original n+1 to the end to the end of the list, thus obtaining a new list a of length n+2.

n,q=map(int,input().split())
a=[0]*(n+10)
b=[0]*(n+10)

#a的0位是0,第1位到第n位是输入的数,第n+1位起往后都是0
a=[0]+list(map(int,input().split()))+a[n+1:]
for i in range(1,n+1):
    b[i]=a[i]-a[i-1]#初始化b数组
    
while q:
    l,r,c=map(int,input().split())
    b[l]+=c
    b[r+1]-=c
    q-=1
    
#a数组没有用了,将a更新一遍
for i in range(1,n+1):
    a[i]=a[i-1]+b[i]
    print(a[i],end=' ')

3. Difference Matrix

insert image description here

Writing method one:

def insert(matrix,x1,y1,x2,y2,c):#差分数组
    matrix[x1][y1]+=c
    matrix[x2+1][y1]-=c
    matrix[x1][y2+1]-=c
    matrix[x2+1][y2+1]+=c

def main():
    n, m, q = map(int, input().split())
    matrix=[[0 for i in range(m+10)] for j in range(n+10)]#定义二维数组
    for i in range(1,n+1):
        row =list(map(int, input().split()))
        for j in range(m):
            insert(matrix,i,j+1,i,j+1,row[j])
            
    for i in range(q):
        x1,y1,x2,y2,c=map(int,input.split())
        insert(matrix,x1,y1,x2,y2,c)
        
    for i in range(1,n+1):
        for j in range(1,m+1):
            matrix[i][j]+=matrix[i-1][j]+matrix[i][j-1]-matrix[i-1][j-1]
            print(matrix[i][j],end=" ")
        print()

if __name__=="__main__":
    main()

Writing method two:

print(" ".join(map(str,dt[i][1:m+1])))

This line of code converts the elements in the list dt[i][1:m+1] into strings, concatenates them with spaces, and prints them out. in:

  1. map(str, dt[i][1:m+1]) means to convert each element in the list dt[i][1:m+1] into a string type;
  2. " ".join(…) means to join the elements in the string list with spaces to form a new string;
  3. print(…) means to print out the concatenated string.
def insert(b,x1,y1,x2,y2,c):
    b[x1][y1] += c
    b[x2+1][y1] -= c
    b[x1][y2+1] -= c
    b[x2+1][y2+1] += c

n,m,q = map(int,input().split())
ls = []
dt = [[0 for _ in range(1010)] for _ in range(1010)]
for i in range(n):
    ls.append(list(map(int,input().split())))
for i in range(1,n+1):
    for j in range(1,m+1):
        insert(dt,i,j,i,j,ls[i-1][j-1])
while q >0:
    q -= 1
    x1,y1,x2,y2,c = map(int,input().split())
    insert(dt,x1,y1,x2,y2,c)
for i in range(1,n+1):
    for j in range(1,m+1):
        dt[i][j] +=dt[i-1][j]+dt[i][j-1] - dt[i-1][j-1]
for i in range(1,n+1):
    print(" ".join(map(str,dt[i][1:m+1])))

4. Increase and decrease sequence

The difference solves the problem of simultaneous increase or decrease in a section of area
. Add a constant c to the interval [L, R], then b[L] += c , b[R + 1] -=c

Find the difference sequence b of a, where b1 = a1, b(i) = a(i) - a(i - 1) (2 <= i <= n). Let b(n + 1) = 0, the operation of the title on the sequence a is equivalent to selecting any two numbers in b1, b2...b(n + 1) each time, adding 1 to one and subtracting 1 from the other. The goal is to change b2,b3,...bn to all 0s. The final sequence a is composed of n b1

The method of choosing two numbers can be divided into four categories
1, 2 <= i , j <= n (priority)
2, i = 1, 2 <= j <= n
3, 2 <= i <= n , j = n + 1
4, i = 1, j = n + 1 (doesn't make sense)

Let the sum of positive numbers in b2, b3...bn be p, and the absolute value of the sum of negative numbers be q. First, try to perform type 1 operations by matching positive and negative numbers, and you can perform min(p,q) times. The remaining |p - q| matches are pairs, each of which can be selected to match b1 or b(n + 1), that is, to perform 2 or 3 types of operations, requiring a total of |p - q| times

In summary, the minimum number of operations is min(p,q) + |p - q|. According to the selection of the 2nd and 3rd operations of |p - q| times, different b1 values ​​in |p - q| + 1 can be generated, that is, the final sequence a may have |p - q| + 1 types

insert image description here

print(f"{max(pos, neg)}\n{abs(pos - neg) + 1}")

This is a way of writing f-string, which is used to format strings. Among them, the part inside the braces will be replaced with the value of the corresponding variable or expression. Specifically:

f"xxx": Indicates that this is an f-string, where xxx is the string content, which can contain ordinary text and brace expressions.
{max(pos, neg)}: Indicates a brace expression, which will be replaced by the maximum value of pos and neg.
\n: Indicates a newline character.
{abs(pos - neg) + 1}: Indicates a brace expression, which will be replaced by the absolute value of the difference between pos and neg plus 1.

n = int(input())
a = [0] * (n + 2)
for i in range(1,n+1):
    x = int(input())
    a[i] += x
    a[i+1] -= x

pos, neg = 0, 0
for i in range(2, n+1):
    if a[i] > 0:
        pos += a[i]
    else:
        neg -= a[i]

print(f"{
      
      max(pos, neg)}\n{
      
      abs(pos - neg) + 1}")

Guess you like

Origin blog.csdn.net/qq_51408826/article/details/129224213