See Aufgabe3
A solution to the 3rd problem of the 38th Bundeswettbewerb Informatik (German Olympiad in Informatics)