Untitled

mail@pastecode.io avatar
unknown
python
7 months ago
1.2 kB
2
Indexable
Never
from collections import defaultdict

with open('input-5.txt', 'r') as f:
    parts = f.read().split('\n\n')

_, reqs = parts[0].split(': ')
seeds = [int(x) for x in reqs.split(' ')]
intervals = [(a, a+b) for a,b in zip(seeds[::2], seeds[1::2])]
intervals = sorted(intervals, reverse=True)

for fromto in parts[1:]:
    bounds_val = defaultdict(lambda: 0)
    bounds = set()
    for r in fromto.split('\n')[1:]:
        new, old, ran = [int(x) for x in r.split(' ')]
        bounds.add(old)
        bounds.add(old + ran)
        bounds_val[old] = new - old
    mapping = [(x, bounds_val[x]) for x in sorted(list(bounds), reverse=True)]

    new_intervals = []
    curr_delta = 0
    while intervals:
        x1, x2 = intervals.pop()
        while mapping and mapping[-1][0] <= x1:
            _, curr_delta = mapping.pop()
        if len(mapping) == 0 or mapping[-1][0] >= x2:
            new_intervals.append((x1 + curr_delta, x2 + curr_delta))
        elif mapping[-1][0] < x2:
            new_intervals.append((x1 + curr_delta, mapping[-1][0] + curr_delta))
            intervals.append((mapping[-1][0], x2))
    intervals = sorted(new_intervals, reverse=True)

print(intervals[-1][0])

Leave a Comment