一、第一题:空调
解题思路:差分
希望P减掉T后就相当于从0到New_P,想到得到New_P只需要对全0数组进行若干次区间加操作,所以只需要对New_P数组进行差分,累加正数和负数,哪个绝对值大答案就是那个。
【Python程序代码】
python
from math import *
n = int(input())
p = list(map(int,input().split()))
t = list(map(int,input().split()))
k = [0]*len(p)
for i in range(n):p[i]-=t[i]
k[0]=p[0]
for i in range(1,n):k[i]=p[i]-p[i-1]
a1,a2=0,0
for i in range(n):
if k[i]<0:a1+=k[i]
else:a2+=k[i]
if fabs(a1)>fabs(a2):print(int(fabs(a1)))
else:print(int(fabs(a2)))
二、第二题:差分
解题思路:差分
差分模板题。
【Python程序代码】
python
n,m = map(int,input().split())
a = [0] + list(map(int,input().split()))+[0]
cc = [0]*(n+5)
for i in range(m):
l,r,c = map(int,input().split())
cc[l]+=c
cc[r+1]-=c
for i in range(1,n+1):
cc[i]+=cc[i-1]
a[i]+=cc[i]
for i in range(1,1+n):
print(a[i],end=' ')
三、第三题:差分矩阵
解题思路:二维差分
二维差分模板题
【Python程序代码】
python
n,m,q = map(int,input().split())
a = [[0]*(m+5)]
for i in range(n):
a.append([0]+list(map(int,input().split())))
s = [[0]*(m+5) for _ in range(n+5)]
for i in range(q):
x1,y1,x2,y2,c = map(int,input().split())
s[x1][y1]+=c
s[x2+1][y2+1]+=c
s[x1][y2+1]-=c
s[x2+1][y1]-=c
for i in range(1,n+1):
for j in range(1,m+1):
s[i][j]+=s[i-1][j]+s[i][j-1]-s[i-1][j-1]
a[i][j]+=s[i][j]
print(a[i][j],end=' ')
print()
四、第四题: 棋盘
解题思路:差分
差分+取模
【Python程序代码】
python
n,m = map(int,input().split())
a = [[0]*(n+5) for _ in range(n+5)]
for i in range(m):
x1,y1,x2,y2 = map(int,input().split())
a[x1][y1]+=1
a[x1][y2+1]-=1
a[x2+1][y1]-=1
a[x2+1][y2+1]+=1
for i in range(1,n+1):
for j in range(1,n+1):
a[i][j] += a[i-1][j]+a[i][j-1]-a[i-1][j-1]
t = a[i][j]%2
print(str(t),end='')
print()
五、第五题: 重新排序
解题思路:差分+排序
差分+排序
【Python程序代码】
python
n = int(input())
a = list(map(int,input().split()))
ta = [0]*(n+5)
for i in range(n):ta[i+1]=ta[i]+a[i]
m = int(input())
c = [0]*(n+2)
yy = 0
for i in range(m):
l,r = map(int,input().split())
yy += ta[r]-ta[l-1]
c[l]+=1
c[r+1]-=1
for i in range(1,n+1):c[i]+=c[i-1]
a.sort(reverse=True)
c.sort(reverse=True)
res = 0
for i in range(n):
res += a[i]*c[i]
print(res-yy)