Longest passage without traffic lights

Added: 2025-09-13 00:35:05

Question Image

Longest passage without traffic lights

Answer

✏️ Edit
import sys
from bisect import bisect_left
from collections import Counter
import heapq

def main():
    data = list(map(int, sys.stdin.read().split()))
    if len(data) < 2:
        return
    x, n = data[0], data[1]
    ps = data[2:2+n]

    # Sorted list of light positions (with boundaries 0 and x)
    lights = [0, x]

    # Multiset of gaps: counts and a max-heap (store negatives)
    counts = Counter()
    counts[x] = 1
    heap = [-x]

    out = []

    for p in ps:
        i = bisect_left(lights, p)
        left = lights[i-1]
        right = lights[i]

        # Remove old gap
        old = right - left
        counts[old] -= 1

        # Add new gaps
        g1 = p - left
        g2 = right - p
        counts[g1] += 1
        counts[g2] += 1
        heapq.heappush(heap, -g1)
        heapq.heappush(heap, -g2)

        # Insert light position
        lights.insert(i, p)

        # Get current max gap (clean lazy-deleted entries)
        while heap and counts[-heap[0]] == 0:
            heapq.heappop(heap)
        out.append(str(-heap[0]))

    print(" ".join(out))

if __name__ == "__main__":
    main()