Python实现【数字游戏】
def solve():
import sys
while True:
# 读取第一行
line1 = sys.stdin.readline()
if not line1: # 检查是否到达文件末尾
break
n, m = map(int, line1.strip().split())
# 读取第二行
line2 = sys.stdin.readline()
a = list(map(int, line2.strip().split()))
# 检查是否存在满足条件的子数组
found = False
prefix = 0
mod_map = {0: -1} # 初始状态,前缀和为0的位置为-1
for i in range(n):
prefix = (prefix + a[i]) % m
if prefix in mod_map:
found = True
break
mod_map[prefix] = i
print(1 if found else 0)
solve()
方法思路
- 前缀和与模运算:利用前缀和数组来快速计算任意连续子数组的和。同时,利用模运算的性质来优化判断过程。
- 哈希表记录模值:维护一个哈希表来记录前缀和模m的值及其出现的位置。如果在遍历过程中发现相同的模值再次出现,说明存在满足条件的子数组。