N, K = map(int, input().split())
a = []
s = []
s.append(0)
for i in range(N):
x = int(input())
a.append(x)
s.append(x+s[i])
res = 0
for i in range(0, N):
for j in range(i+1, N+1):
t = s[j] - s[i]
if(t>0 and t%K==0):
res+=1
print(res)
我们考虑更简便的解题方式
我们直观地会理解为,满足条件的序列表达式为:
s[j]-s[i] %k==0,(i-1, j-1)
但是我们换一种思路, 对前缀和先取模:
(s[j]%k)-(s[i] %k)==0,(i-1, j-1)
我们就只用保证二者取模后的值相等就可以保证上式成立了
用字典存放模的值这样就可以不用暴力循环求解了
N, K = map(int, input().split())
s = [0]
dp={0:1}
res = 0
for i in range(N):
x = int(input()) + s[i]
s.append(x)
xmod = x%K
res+=dp.get(xmod, 0)
dp[xmod] = dp.get(xmod, 0)+1
print(res)