aoc2024/d09/part1.py

37 lines
708 B
Python

import sys, os
I = list(map(int, sys.stdin.read().strip()))
def sum_n(a, b):
return (b-a+1)*(a+b)//2
I = I
j = 0
b = 0
res = 0
id = len(I)//2 # last ID
x = I[len(I)-1]
for i in range(len(I)//2):
if len(I)-2*j-1 - 2*i == 0:
res += sum_n(b, b+x-1)*i
break
nb = b + I[2*i]
res += sum_n(b, nb-1)*i
b = nb
space = I[2*i+1]
while space > 0:
if x > space:
nb = b + space
res += sum_n(b, nb-1)*id
x -= space
space = 0
else:
nb = b + x
res += sum_n(b, nb-1)*id
id -= 1
space -= x
j += 1
x = I[len(I)-2*j-1]
b = nb
print(res)