蓝桥杯 第四十三天 模板

目录

1.逆序对的数量

2.整数二分

3.前缀和

4.差分

5.双指针

(1)

(2)

(3)


1.逆序对的数量

def mergesort(l,r):
    if l>=r:
        return
    global res
    mid=l+r>>1
    mergesort(l,mid)
    mergesort(mid+1,r)
    temp=[]
    i,j=l,mid+1
    while i<=mid and j<=r:
        if a[i]>a[j]:
            res+=mid-i+1
            temp.append(a[j])
            j+=1
        else:
            temp.append(a[i])
            i+=1
    while i<=mid:
        temp.append(a[i])
        i+=1
    while j<=r:
        temp.append(a[j])
        j+=1
    for i in range(l,r+1):
        a[i]=temp[i-l]
    return

a=[6,202,100,301,38,8,1]
res=0
mergesort(0,len(a)-1)
print(a)
print(res)

2.整数二分

def firstsearch(num):
    left,right=0,n-1
    while left=num:
            right=mid
        else:
            left=mid+1
    if a[left]==num:
        return left
    else:
        return -1
def lastsearch(num):
    left,right=0,n-1
    while left

3.前缀和

n,r=map(int,input().split())
N=5005
maxx,maxy=-1,-1
adj=[[0 for i in range(N+1)]for j in range(N+1)]
for i in range(n):
    x,y,z=map(int,input().split())
    x+=1
    y+=1
    adj[x][y]+=z
    maxx=max(x,maxx)
    maxy=max(y,maxy)
for i in range(1,maxx+1):
    for j in range(1,maxy+1):
        adj[i][j]+=adj[i-1][j]+adj[i][j-1]-adj[i-1][j-1]
ans=-1
for i in range(1,maxx+1):
    for j in range(1,maxy+1):
        leftx,lefty=i,j
        rightx=min(maxx,leftx+r-1)
        righty=min(maxy,lefty+r-1)
        curans=adj[rightx][righty]+adj[leftx-1][lefty-1]-adj[rightx][lefty-1]-adj[leftx-1][righty]
        ans=max(ans,curans)
print(ans)

4.差分

n=int(input())
a=[0]
b=[0]
for i in range(n):
    a.append(int(input()))
    b.append(a[i+1]-a[i])
pos=0
neg=0
for i in b[2:]:
    if i>0:
        pos+=i
    else:
        neg+=i
print(min(abs(neg),pos)+abs(abs(neg)-pos))
print(abs(abs(neg)-pos)+1)

5.双指针

(1)

n=int(input())
a=list(map(int,input().split()))
ans=1
vis=[False for i in range(max(a)+1)]
i=1
j=0
vis[i]=True
while i

(2)

n,m,x=map(int,input().split())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
j=m-1
for i in range(n):
    while j>0 and a[i]+b[j]>x:
        j-=1
    if j>0 and a[i]+b[j]==x:
        print(i,j)

(3)

# 3 5
# 1 3 5
# 1 2 3 4 5
n,m=map(int,input().split())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
i=0
for j in range(m):
    if b[j]==a[i]:
        i+=1
if i==n:
    print(True)
else:
    print(False)

# 3 5
# 1 3 5
# 1 2 3 4 5
n,m=map(int,input().split())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
dp=[[False for i in range(len(b)+1)]for j in range(len(a)+1)]
dp[0][0]=True
for i in range(1,n+1):
    for j in range(1,m+1):
        if a[i-1]==b[j-1]:
            dp[i][j]=dp[i-1][j-1]
        else:
            dp[i][j]=dp[i][j-1]
for i in dp:
    print(i)
print(dp[-1][-1])

你可能感兴趣的:(蓝桥杯,蓝桥杯,拓扑学,职场和发展)