I am working on this problem on CSES, Traffic Lights:
There is a street of length whose positions are numbered 0,1,…,. Initially there are no traffic lights, but sets of traffic lights are added to the street one after another.
Your task is to calculate the length of the longest passage without traffic lights after each addition.
Input
The first input line contains two integers and : the length of the street and the number of sets of traffic lights.
Then, the next line contains n integers 1,2,…,: the position of each set of traffic lights. Each position is distinct.
Output
Print the length of the longest passage without traffic lights after each addition.
Constraints
- 1 ≤ ≤ 109
- 1 ≤ ≤ 2⋅105
- 0 < <
Example
Input:
8 3 3 6 2Output:
5 3 3
So to effectively solve a problem like this, I need a data structure in Python similar to a list but the search and deletion of elements need to be O(1) or more like a data structure similar to sets but I need to be able to insert multiple same elements and also preserve order. My code for the problem is:
from collections import defaultdict
from bisect import bisect_right , insort
x , n = list(map(int , input().split()))
arr = list(map(int , input().split()))
lens = defaultdict(int)
lens[x] = 1
lights = [0,x]
for ele in arr:
idx = bisect_right(lights , ele)
to_be_removed = lights[idx] - lights[idx-1]
lens[to_be_removed] -= 1
lens[lights[idx]-ele] += 1
lens[ele-lights[idx-1]] += 1
insort(lights , ele)
print(max([x for x in lens.keys() if lens[x]]) , end =" ")
However this code is slow. There is a data structure called multi-sets in c++. However couldn't find a similar data structure in python. Any help appreciated.