Editorial for CTU Open Contest 2017 - Ice Cream Samples
Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
Submitting an official solution before solving the problem yourself is a bannable offence.
Submitting an official solution before solving the problem yourself is a bannable offence.
- Naive solution – fix a starting stand and consecutively include following stands until all brands of ice cream are collected
- This solution runs in at least time ⇒ TLE
- The faster solution is to use two-pointer technique to dynamically enlarge and shorten currently observed sequence of stands
- In the beginning, the sequence is empty
- We must enlarge the sequence if there are still some brands yet to be collected
- Conversely, if all brands have been collected, we can shorten the sequence
We still have two issues to solve:
- First, we need to effectively calculate the amount of different brands that have been collected
- Solution is simple – keep a frequency array of size , i.e. for each brand, dynamically store the number of collected samples
- Then, while extending the sequence, we increase the count of different brands on the first occurrence of a brand's sample
- While shortening the sequence, we decrease the count of different brands on the last occurrence of a brand's sample
- Secondly, as the stands are positioned circularly, the solution might span over the last stand to the first ones
- It suffices to go through the input twice (imagine as if the input was concatenated with itself once)
- ⇒ By combining mentioned techniques, we obtain an approach that runs in time linear with the amount of samples on the input
Comments